Submit form when a radiobox is checked - javascript

I've read a few questions that meet this description but I'm still struggling. I've read this submit-form-when-checkbox-is-checked-tutorial
Can't seem to get a form to submit when a radiobox is checked. I've tried using .click and .on('change')
Here is my code, the jquery is in a php loop.
<script type="text/javascript">
$(document).ready(function() {
$('input[name=choice-<?php echo $id; ?>]').click(function() {
$('#assessment-form-<?php echo $id; ?>').submit(function(e) {
alert('It works :)');
});
});
});
</script>
<form id="assessment-form-456" method="post" action="">
<ul class="clearfix">
<li><input type="radio" name="choice-456" id="t-456" value="yes">Yes</li>
<li><input type="radio" name="choice-456" id="f-456" value="no">No</li>
<li><input type="radio" name="choice-456" id="na-456" value="na">n/a</li>
</ul>
<input type="submit">
</form>

This is your problem:
$('#assessment-form-<?php echo $id; ?>').submit(function(e) {
alert('It works :)');
});
Instead of submitting the form, you are adding an event listener that will trigger when the form is submitted.
You should not pass any arguments to the function:
$('#assessment-form-<?php echo $id; ?>').submit();
See the jQuery manual; you need the shortcut for the trigger method in order to trigger the form submit.

It attribute values should be wrapped in quotes :
$('input[name="choice-<?php echo $id; ?>]"')
Like this one :
$(document).ready(function() {
$('input[name="choice-456"]').change(function() {
alert('It works :)');
$('#assessment-form-456').submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="assessment-form-456" method="post" action="">
<ul class="clearfix">
<li>
<input type="radio" name="choice-456" id="t-456" value="yes">Yes</li>
<li>
<input type="radio" name="choice-456" id="f-456" value="no">No</li>
<li>
<input type="radio" name="choice-456" id="na-456" value="na">n/a</li>
</ul>
<input type="submit">
</form>

Related

Echo radio button value without using submit button in php

I want to echo the selected radio button value without using submit button. I want to display the value of radio button when it is selected. Here is the code.
<?php
if(!empty($_GET['a1'])){
$selected = $_GET['a1'];
}
else{
//if no option was selected, set home as default
$selected = 'home';
}
?>
<form action="" method="post">
<input type="radio" name="a1" value="home" /> Home <?php echo ($selected == 'home' ? 'This was selected!' : '');?> </br>
<input type="radio" name="a1" value="site1" /> Site 1 <?php echo ($selected == 'site1' ? 'This was selected!' : '');?> </br>
<input type="radio" name="a1" value="site2" /> Site 2 <?php echo ($selected == 'site2' ? 'This was selected!' : '');?> </br>
</form>
I want the output in the following format
Here is your solution....
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>//jQuery Plugin
<?php
if(!empty($_GET['a1'])){ $selected = $_GET['a1'];}
else{ $selected = 'home';}
?>
<form action="" method="post">
<label>
<input type="radio" name="a1" value="home" /> Home
</label></br>
<label>
<input type="radio" name="a1" value="site1" /> Site 1
</label></br>
<label>
<input type="radio" name="a1" value="site2" /> Site 2
</label></br>
</form>
<span class="r-text"><?php echo $selected;?></span>
<script>
$('input[type=radio]').click(function(e) {//jQuery works on clicking radio box
var value = $(this).val(); //Get the clicked checkbox value
$('.r-text').html(value);
});
</script>
I'm not sure how you want to do a clientside manipulation with PHP(!!!) but this is a jquery solution for displaying the value of radio button when it is selected:
$('#myform input[type=radio]').on('change', function(event) {
var result = $(this).val();
$('#result').html(result);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="" method="post">
<input type="radio" name="a1" value="home" /> home</br>
<input type="radio" name="a1" value="site1" /> site1</br>
<input type="radio" name="a1" value="site2" /> site2</br>
<div id="result"></div>
</form>
You need to use the onchange event of the radio buttons with javascript/jquery.
PHP runs server-side, not client-side, so without sending client-side changes to the server, it can't output stuff based on them: you'd need to send a $_POST or a $_GET request, either by submitting the form or using AJAX. Not necessary for this.
<div id="radioMsg"></div>
<form action="" method="post">
<input type="radio" name="a1" value="home" onchange="showRadio()" /> Home <?php echo ($selected == 'home' ? 'This was selected!' : '');?> </br>
<input type="radio" name="a1" value="site1" onchange="showRadio()" /> Site 1 <?php echo ($selected == 'xyz' ? 'This was selected!' : '');?> </br>
<input type="radio" name="a1" value="site2" onchange="showRadio()" /> Site 2 <?php echo ($selected == 'zbc' ? 'This was selected!' : '');?> </br>
</form>
Meanwhile in showRadio():
function showRadio(){
var radioVal = $("input[name='a1']:checked").val();
if(radioVal) {
$( "#radioMsg" ).html("<p>"+radioVal+"</p>");
}
}
I'm not sure where you want the changed button's value outputted, so I'm putting it into that div just as an example.
To define the onchange event in an external stylesheet instead of inline:
$( "input[name='a1']" ).change(function(){
... (showRadio's contents go here)
});

Div not replacing after form submission

Hey I am making a simple form. The person just has to select among the two options - Male or female and then if any one radio button is checked, on submit I want the div to be replaced by another div. I've tried to accomplish this with a javascript function, but this doesn't seem to work for me.
<?php
$genderErr = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["gender"])) {
$genderErr = "<div class='alert'>Please select a gender.</div>";
} else {
?>
<script type="text/javascript">
$(document).ready(function(){
$("#2").css('display', 'block');
$("div#1").replaceWith( $( "#2" ) );
});
</script>
<?php }}
?>
<div id="1">
<h1>Step 1: Choose your gender</h1>
<div>
<form id="genderform" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<input type="radio" name="gender" value="male" <?php if (isset($gender) && $gender=="male");?>>Male<br />
<input type="radio" name="gender" value="female" <?php if (isset($gender) && $gender=="female");?>>Female<br />
<input form="genderform" id="submit" name="submit" type="submit" value="Submit">
<?php echo $genderErr;?>
</form>
</div>
</div>
<div id="2" style="display:none">
<h1>Step 2:</h1>
</div>
I don't know what I am doing wrong because if I replace the javascript with header("Location:http://example.com"); it works fine.
Okay I found out the issue. Though the same code worked on another script without any issue, probably because it was Bootstrap and already had imported the jquery library. The simple little fix for the whole trouble was adding the jquery library to <head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
Add this function to your script $("#submit").click(function()so when you click the script will trigger.
$("#submit").click(function() {
$("#2").css('display', 'block');
$("div#1").replaceWith( $( "#2" ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1">
<h1>Step 1: Choose your gender</h1>
<div>
<form id="genderform" action="#" method="post">
<input type="radio" name="gender" value="male"> Male<br />
<input type="radio" name="gender" value="female">Female<br />
<input form="genderform" id="submit" name="submit" type="submit" value="Submit">
</form>
</div>
</div>
<div id="2" style="display:none">
<h1>Step 2:</h1>
</div>
try this
$('#myForm').submit(function(){
var field1 = $("#field1").serialize(); // If this doesn't work just remove the serialize()
var field2 = $("#field2").serialize();
$.ajax({
type: "POST",
url : "???", //your processing page URL instead of ???
data: "&field1="+field1+"&field2="+field2,
success: function(){
$("#formHolder").html("Your static content");
}
});
});

Form elements added after AJAX and php script not transfered to $_POST

I am using AJAX to get the value of the element chosen in a select input and to launch a PHP script that returns some input checkboxes fields.
Here is what it looks like :
HTML
<form method="post" action="liens_chra.php" name="Form" id="Form">
<label for="id_turbo">Turbo</label>
<select name="id_turbo" size="1" id="id_turbo">
<option value="10970">TM1761178</option>
<!-- and more -->
</select>
<div id="choix_reffab">
<!-- checkboxes appear here -->
</div>
<p class="form ">
<input type="submit" name="valider" value="Enregistrer">
</p>
<!-- something I tried too
<input type="button" id="submitevent" value="Enregister">
<script type="text/javascript" >
$('#submitevent').click(function() {
$("#Form").submit();
});
</script> -->
</form>
JQuery/AJAX
$("#id_turbo").change(function(){
var id_turbo = $("#id_turbo").val();
$.ajax({type: "POST",
url: "<?=URLSITEWEB;?>admin/outils/ajax/liste_Reffab.php",
data: "id_turbo="+id_turbo+"",
error: function(){
/*alert(id_famille+" \n ne passent pas.");*/
},
success: function(data){
$("#choix_reffab").html(data);
}
});
});
PHP
/* things */
foreach ($fabTab as $fab) {
$chaine .= '<input type="checkbox" "name=tabreffab[]" id="'.$fab.'" value="'.$fab.'" /><label for="'.$fab.'">'.$fab.'</label>';
}
echo $chaine;
So, when the user selects a value, some checkboxes appears.
My problem is that the data I want is not transfered to $_POST, and here is the result :
var_dump($_POST['tabreffab']) // is NULL, others values are ok
I'm fairly new to AJAX & JQuery, so I have no idea what to do. I tried submitting the form using JQuery, made no changes.
I got your issues when you return your checkbox your mistake is at name property of element.
In your code "name=tabreffab[]" Replace with name = "tabreffab[]"
$chaine .= ''.$fab.'';
Insted of above write like below code
$chaine .= '<input type="checkbox" name = "tabreffab[]" id="'.$fab.'" value="'.$fab.'" /><label for="'.$fab.'">'.$fab.'</label>';
checkboxes value will display in $_POST[] only on selecting a value
try in a editor
<?php
echo "<pre>";
print_r($_POST);
?>
<form id="sampleName" name ="sampleName" method="post" action="">
<textarea id="testID" name="textAreaName"></textarea>
<input type="text" name="text1" />
<input type="checkbox" name="check" value="1"/>
<input type="checkbox" name="check" value="2"/>
<input type="checkbox" name="check" value="3"/>
<input type="submit" value="submit">
</form>
The problem is in your Ajax call, specifically in the data part. It takes a json formatted object. The right way to write this is data:{id_turbo:"id_turbo_value"} not as what you used - data: "id_turbo="+id_turbo+""

Single radio select on two forms

I have two radio buttons which correspond to two different forms.
Depending on the selected radio, I want to accomplish two different actions, thus the reason why I have two forms.
The problem I'm having is that single-radio select works when the two radios are on a single form. If, by any chance they are in two different forms, the single selection doesn't work.
Both radios have the same name, but I don't know how to force single select based on two different forms.
I'm using jQuery (not for radios selection, but the jQuery is there) so although I would prefer not to use jQuery for this action, if it comes down to it, I'm ok with that.
Could anyone provide a solution or a pointer in the solution direction for this?
Best Regards,
EDIT
I'm placing some code at request
<div class="payment-details-account-top">
<form id="payment-details-form-card" action="<?php echo Mage::getUrl('orderform/index/changedpayment'); ?>" method="POST">
<div class="row all-steps">
<div class="col-md-12">
<input type="radio" name="payment-type" value="<?php echo $this->__('Betale med kort') ?>" id="payment-with-card" class="css-checkbox" <?php if ($ba->getMethodCode() == 'payex2'): ?> checked <?php endif; ?> onclick="this.form.submit();">
<label for="payment-with-card" class="css-radio-label"></label>
<input type="submit" name="payment-with-card" id="payment-with-card" value="<?php echo $this->__('Betale med kort') ?>" class="top-payment-buttons" />
<div class="creditcards"></div>
<!-- <span class="payment-method-message"><?php if ($ba->getMethodCode() == 'payex2') echo $message; ?></span> -->
</div>
</div>
</form> <!-- Close "payment-details-form-card" form -->
</div>
<div class="payment-details-account-bottom">
<form id="payment-details-form" action="<?php echo Mage::getUrl('orderform/index/changedpayment'); ?>" method="POST">
<div class="col-md-12">
<input type="radio" name="payment-type" value="<?php echo $this->__('Betale med faktura') ?>" id="payment-with-faktura" class="css-checkbox" <?php if ($ba->getMethodCode() != 'payex2'): ?> checked <?php endif; ?> >
<label for="payment-with-faktura" class="css-radio-label"></label>
<input type="button" name="payment-with-faktura" id="payment-with-faktura" value="<?php echo $this->__('Betale med faktura') ?>" class="bottom-payment-buttons" />
<div class="row">
<ul>
<li class="row">
<div id="billing-submit" style="display: none;">
<input type="reset" name="submit-cancel" id="billing-cancel" value="AVBRYT" class="btn-grey" />
<input type="submit" name="submit-payment" id="submit-payment" value="<?php echo $this->__('Bekreft') ?>" class="btn-green" />
</div>
</li>
</ul>
</div>
</div>
</form>
</div>
Without seeing all of your code, it is hard to tell if you would be better off handling this in a different manner, such as:
Use a tab set with each form on a different tab.
Use a single form, but change the form's action based on the radio buttons.
If you really want to use two forms with radio buttons like that, you either have to place the radio buttons outside the forms or handle the selecting/unselecting yourself.
(1) Placing the radio buttons outside the forms.
HTML:
<label><input type="radio" name="formSelect" value="#form1" checked="checked"/>Form 1</label>
<form id="form1" class="form">
<input type="text"/>
</form>
<label><input type="radio" name="formSelect" value="#form2"/>Form 2</label>
<form id="form2" class="form">
<input type="text"/>
</form>
<button type="button" id="submitBtn">Submit</button>
JQuery:
$('#submitBtn').click(function() {
var $form = $($('input[name=formSelect]:checked').val());
alert('submitting form: ' + $form.attr('id'));
//$form.submit();
});
jsfiddle
(2) Handling the selecting/unselecting yourself/.
HTML:
<form id="form1" class="form">
<label><input type="radio" class="formSelect" checked="checked"/>Form 1</label>
<input type="text"/>
</form>
<form id="form2" class="form">
<label><input type="radio" class="formSelect"/>Form 2</label>
<input type="text"/>
</form>
<button type="button" id="submitBtn">Submit</button>
JQuery:
$('.formSelect').change(function() {
$('.form').not($(this).closest('form')).find('.formSelect').prop('checked', false);
});
$('#submitBtn').click(function() {
var $form = $('.formSelect:checked').closest('form');
alert('submitting form: ' + $form.attr('id'));
//$form.submit();
});
jsfiddle
Really, no vanilla JS answer even though OP explicitly mentioned a preference?
Simple as this:
var options = document.getElementsByName('mygroup');
document.body.addEventListener('click', function(e) {
if (e.target.name === 'mygroup') {
for (var i = 0; i < options.length; i++)
options[i].checked = false;
e.target.checked = true;
}
}, false);
See it here: http://jsbin.com/mefibi/1/edit?html,js,output
Most of these answers are almost there and actually provide a path in the right direction..
Since the forms code is a lot more complex than the sample I posted, here's the actual implementation:
$('#payment-with-faktura').on('click', function(){
$('#payment-with-card').removeAttr("checked");
$('.billing-address-list input').each(function() {
$(this).attr({
'disabled': 'disabled'
});
});
$(".col-order-12").slideDown(300);
$(".prepaid-extra-method2").slideDown(300);
if (validateBillingAddress()) {
$(".payment-button-submit").removeAttr("disabled");
} else {
$(".payment-button-submit").attr("disabled", "disabled");
}
});
$('#payment-with-card').on('click', function(){
$('#payment-with-faktura').removeAttr("checked");
$("#payment-details-form").find('input[type="text"]').val("");
$(".prepaid-extra-method2").slideUp(300);
$(".col-order-12").slideUp(300);
if (validateBillingAddress()) {
$(".payment-button-submit").removeAttr("disabled");
} else {
$(".payment-button-submit").attr("disabled", "disabled");
}
});
If I understood correctly, there will be 2 same named radio boxes inside 2 different forms and only one of radio box could be selected at a time. A possible way to achieve this could be like this:
var options = $('form input:radio');
options.click(function() {
options.prop('checked', false);
$(this).prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form><input type="radio" name="opt"/></form>
<form><input type="radio" name="opt" /></form>
It is basically clean all 'selected' state and re-check the clicked one

how to Link html form and anchor tag

I am new to HTML. I want the following to be done in html.
if(link is clicked) {
process one form tag
}
else {
some other form tag
}
this is my form tag .
<form name="input" action="abc.pl" method="get" id="sel">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
I want a link such that if i click on the link the above forms input(i mean the checkboxes value) should be taken and the link should process another .pl file in action ...
I think you could try to change the form action dynamically when user clicked the link by using jQuery. Here is a simple example:
HTML
<form id="form1" action="http://jimmy.right-pet.cc/test.php" method="post">
<legend>Test</legend>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name"/>
<input id="submit-btn" type="submit" value="submit"/>
</fieldset>
</form>
<a id="link" href="#">change form action link</a>
JS
<script>
$(function(){
$("#link").click(function(){
$("#form1").attr("action","http://jimmy.right-pet.cc/test2.php");
});
});
</script>
And try to use the browser dev tool to check if the form action is changed after you clicked the link.
Here is a jsFiddle demo.
Hope it helpful.
Not strictly an answer to the question, but still a solution to the problem.
From the comments:
Don't do that. Submit to one server side URI. Do it with submit buttons. Look at the value of the submit button in the form data to determine which branch of code to run on the server. – Quentin 1 hour ago
#Quentin Please Give me an example . I am new to HTML
In the HTML.
<form name="input" action="abc.pl" method="get" id="sel">
<label>
<input type="checkbox" name="vehicle" value="Bike">
I have a bike
</label>
<label>
<input type="checkbox" name="vehicle" value="Car">
I have a car
</label>
<input type="submit" name="sub" value="Some Action">
<input type="submit" name="sub" value="Some Other Action">
</form>
And then in abc.pl:
use strict;
use warnings;
use CGI;
my $c = CGI->new;
my $sub = $c->param('sub');
unless ($c) {
# No submit value was detected so either perform a default
# action or return an error
exit;
}
if ($c eq "Some Action") {
# Do one thing
} elseif ($c eq "Some Other Action") {
# Do another thing
}

Categories

Resources