Ken
Ken

Reputation: 57

Capturing values from outside a Form with Javascript

Full page is at http://f14.co/auto-search/reno

I have the following checkbox set up outside a form:

<div class='span5' style='margin-left:0px !important;'>
    <label for='model0'>
    <input type="checkbox" name="model0x" id="model0x"
    value="Accord" style='margin-top:-5px !important;'> Accord</label>
</div>      

I have this javascript between the checkbox and the form:

<script>
    if($("#model0x").is(':checked')){
      $("#model0_is_checked").val($("#model0x").val());
    }else{ 
      $("#model0_is_checked").val("Not Checked"); 
    }   
</script>

Finally, I have this hidden input to call that value inside the form when the item is checked or not:

 <form method="post" class="form-horizontal" id="final_form" action="send_mail.php">
 <input type="hidden" id="model0_is_checked" name="model0_is_checked">
   MORE FORM STUFF AND SUBMIT BUTTON 
 </form>

No matter what I'm getting no value in the send_mail.php ....what am I doing wrong?

Upvotes: 0

Views: 70

Answers (3)

user2658927
user2658927

Reputation: 11

$('#model0x').click(function(){
    var self=this;
    $("#model0_is_checked").val($(self).is(':checked')?self.value:'Not Checked');
    // do something
});
// or use submit ()

Upvotes: 1

Sean
Sean

Reputation: 12433

Bind the function to the form submit.

<script>
$('#final_form').on('submit',function(){
    if($("#model0x").is(':checked')){
        $("#model0_is_checked").val($("#model0x").val()); }
    else { $("#model0_is_checked").val("Not Checked");}
});
</script>

jsFiddle example http://jsfiddle.net/KZrLp/

Upvotes: 0

Pik&#39;
Pik&#39;

Reputation: 7067

Your Javascript runs once, when the page (or more accurately, the <script> tag) is loaded. You have to make it run when the form is submitted instead:

<script type="text/javascript">
function updateHidden() { // Find a better name ;)
    if($("#model0x").is(':checked'))
        $("#model0_is_checked").val($("#model0x").val());
    else
        $("#model0_is_checked").val("Not Checked");
}
$(document).ready(function() { $('#final_form').submit(updateHidden); });
</script>

P.S. : not tested code

Upvotes: 0

Related Questions