0

I have a HTML form in which the user enters the amout of time he/she intends to spend on several tasks:

<form>
<div class='row radio-online'>
  <div class='col-xs-2'>
    <input type='radio' name='time' id='minutes' value='minutes' />Minutes
  </div>
  <div class='col-xs-2'>
    <input type='radio' name='time' id='hours' value='hours' />Hours
  </div>
</div>
<div>
  <div><input type='text' name='time_task1' id='time_task1' value='' /></div>
  <div><input type='text' name='time_task2' id='time_task2' value='' /></div>
  <div><input type='text' name='time_task3' id='time_task3' value='' /></div>
</form>

What I want is to convert the values entered to minutes or hours, depending on the option selected on the radio group 'time'. I tried this in jQuery:

$("input[name='time']:radio").change(function() {
  if($("input:checked[name='time']:radio").val() == 'minutes') {
// this attempts to get every input that has an id starting with time_task
    $("[id^='time_task']").val($("[id^=time_task]").val() * 60);
  }
  else {
    $("[id^='mins']").val($("[id^=mins]").val() / 60);
  }
});

The problem is when I tried that, it does make the conversion, but only the value of the first input is converted and in addition, its value is copied to all other inputs, but the correct would be each value will have its value converted individually. The examples I've found do just that, but it's not my case. Any suggestions?

2 Answers 2

1

This is because when you do

$("[id^='time_task']").val($("[id^=time_task]").val() * 60);

the selector $("[id^='time_task']") returns multiple elements but as soon as you use .val() it takes the first element.

Instead, loop over each element in the collection like following:

$("[id^='time_task']").each(function(){ $(this).val( $(this).val() * 60) })
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Rhea. Worked perfectly
0

Try the following

$("input[name='time']:radio").change(function() {
  if ($("input:checked[name='time']:radio").val() == 'minutes') {
    $("[id^='time_task']").each(function(){
        $(this).val($(this).val() * 60);
    })
  }
  else {
    $("[id^='time_task']").each(function(){
        $(this).val($(this).val() / 60);
    })
  }
});

We loop over each field instead and set its value accordingly.

1 Comment

Thanks. Exactly what I wanted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.