nippon
nippon

Reputation: 3

How do I change a hidden field's value with jQuery from another input text field?

I have four input fields two text and two hidden.

The HTML:

<input type="text" name="pie1" class="green" id="pie1" value="Hello"/>
<input type="hidden" name="hPie1" value="green">
<input type="text" name="pie2" class="green" id="pie2" value="Goodbye"/>
<input type="hidden" name="hPie2" value="green">

My script code:

<script>
$(document).ready(function(){   
 $('input:text').click(function( ){
  $(this).toggleClass('green red');
 });
})
 </script>

Question: How do I change the value of the hidden field to the coherent text field class that is toggled at the same time I click the input box? Thanks for any help that you can give.

Upvotes: 0

Views: 574

Answers (3)

Willem Mulder
Willem Mulder

Reputation: 13994

$(document).ready(function(){   
 $('input:text').click(function( ){
  $(this).toggleClass('green red');
  $(this).next().val($(this).attr('class'));
 });
})

Should work! Assuming that the hidden inputs always come directly after the text inputs.

Upvotes: 1

Kasihasi
Kasihasi

Reputation: 1072

A first fast solution for your problem.

<script>
$(document).ready(function(){   
    $('input:text').click(function( ){
        $(this).toggleClass('green red');
        $(this).next().val($(this).attr('class'));
     });
})
</script>

Upvotes: 0

Alexander Corwin
Alexander Corwin

Reputation: 1157

after `$(this).toggleClass('green red');

add $('input[name="h' + $(this).name() + '"]').val($(this).val())

note - =$(this).name() element may have incorrect syntax, but that's the idea.

Upvotes: 0

Related Questions