Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Click to Change Form Field Value

I have this code:

<input type="text" name="frameSelection" id="frameSelection" value="Option 1" />
<a id="change">Change to Option 2</a>

When I click on the link I want to change the field value into "Option 2". How can I do that?

like image 598
Ganikkost Avatar asked Dec 21 '11 23:12

Ganikkost


2 Answers

Very simple. Use click to attach an event handler to the click event, and val to set the value:

$("#change").click(function() {
    $("#frameSelection").val("Option 2");
});

As mentioned in other answers, you may want to prevent the default behaviour of the link, but with your code as it currently is in the question (with no href attribute on the a element) that's not necessary. Just bear it in mind if that could change.

like image 185
James Allardice Avatar answered Oct 03 '22 19:10

James Allardice


With jQuery:

$('#change').click(
    function(e){
        e.preventDefault;  // if your a has an href attribute, this prevents the browser
                           // following that link.
        $('#frameSelection').val("Option 2");
    });

References:

  • click().
  • e.preventDefault.
  • val().
like image 30
David Thomas Avatar answered Oct 03 '22 19:10

David Thomas