Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .on click not working on first click

I have a text field that I need to set the value for when a user either chooses an option from a select field or enters text in a text field and hits a link. Both events then close the div that contains the select and text field/link.

The select option works

$(document).on("change", ".select_choice", function(event) {
    var string = $(this).find("option:selected").text();
    $(this).closest(".select_toggle_area").find(".toggle_choices").toggle();
    $(this).closest(".select_toggle_area").find(".target_input").val(string);
});

The text field/link works on the second click. Any time something is entered into the field the link doesn't work on the first click. It hides the div, but doesn't update the value of the target field.

$(document).on("click", ".text_choice_button", function(event) {
    event.preventDefault();
    var string = $(this).closest(".select_toggle_area").find(".text_choice").val();
    $(this).closest(".select_toggle_area").find(".target_input").val(string);
    $(this).closest(".select_toggle_area").find(".toggle_choices").toggle();
});
like image 929
Gabe K Avatar asked May 16 '12 14:05

Gabe K


2 Answers

Unable to replicate

I have fiddled with this and am unable to replicate it: http://jsfiddle.net/DCM48/

Please upload a full fiddle with the issue for further help.

-Lededje

like image 193
lededje Avatar answered Oct 17 '22 16:10

lededje


try using delegate

$(document).ready(function() {
    $("body").delegate("click", ".text_choice_button", function() {
           your code......
    });
});
like image 42
user1045373 Avatar answered Oct 17 '22 14:10

user1045373