Form button submit value don't work - javascript

I got the following form but it dont work.I read plenty of examples but cant understand what I do wrong..
Can someone explain me please why $_POST["choice"] don't work?
I can post whole code if nessesary but I though it dont need..
<form action="2.php" method="POST">
<div class="question">
<?=$question?>
<div class="inline">
<div class="choice1">
<button type="submit" name="choice" class="choice" id="1" value="<?=$ans_array[0]?>" onclick="myFunction()" ><?=$ans_array[0]?></button>
</div>
<div class="choice2">
<button type="submit" class="choice" id="2" name="choice" onclick="myFunction()" value="<?=$ans_array[1]?>"><?=$ans_array[1]?></button>
</div>
</div>
<div class="inline">
<div class="choice1">
<button type="submit" class="choice" id="3" name="choice" onclick="myFunction()" value="<?=$ans_array[2]?>"><?=$ans_array[2]?></button>
</div>
<div class="choice2">
<button type="submit" class="choice" id="4" name="choice" onclick="myFunction()" value="<?=$ans_array[3]?>"><?=$ans_array[3]?></button>
</div>
</div>
</div>
</form>
and then i got the next file 2.php
<?php
echo $_POST["choice"];
$a = $_POST["choice"];
?>
but I get the following
Notice: Undefined index: choice in on line 2
Notice: Undefined index: choice in on line 3

You show the post as a button type. Button type do not exist unless someone pushes the button. If you are doing a submit earlier or allowing ENTER to cause a submit then that is undefined.
You can test this by putting this right in front of choice1
<input type=hidden name=choice value='no button pushed'>
And if you see that, then that's what happened

Thanks everyone for your answers it seemed the problem was on the following javascript as it was blocking the submit from the other buttons.Problem is solved now
<script>
$('form').submit(function (e) {
var form = this;
e.preventDefault();
setTimeout(function () {
form.submit();
}, 1000); // in milliseconds
$("<p>Delay...</p>").appendTo("body");
});
</script>

Related

Why is my checkbox on change not working (AJAX)

This is how my razor code looks like
<form asp-action="Save" asp-controller="ClassesHeld" method="post">
<input asp-for="ClassHeldId" value="#Model.ClassHeldId" hidden />
<div class="form-group">
<label>Student</label>
<input asp-for="#Model.Student" value="#Model.Student" class="form-control" readonly />
</div>
<div class="form-group">
<label>Grade</label>
<input id="Grade"asp-for="Grade" type="number" value="#Model.Grade" class="form-control" min="0" max="5" />
</div>
<div class="form-group">
<label>Attendance</label>
<input id="Attendance" class="form-check-input" asp-for="Attendance" type="checkbox"/>
</div>
<button class="btn btn-primary" type="submit" value="Save">Save</button>
</form>
<script>
$("#Attendance").on("change", function () {
$("#Grade").attr("disabled", this.checked);
});
</script>
Yet for some reason, clicking on the checkbox does nothing at all. I have tried this with simple script as well, and that didn't work either.
document.getElementById('Attendance').onchange = function () {
document.getElementById('Grade').disabled = this.checked;
};
Neither of these worked.
I have even copied some solutions from here (one of them is that last simple scrip with document.getElementbyId, and none of it worked. I have to be missing something simple, but I've been looking at this for the past hour and I still can't figure it out.
I apologize if the question is stupid or noob-level. But I am getting desperate.
EDIT: Simply to add more information, this form works perfectly fine when submitting data, controller saves the stuff to the database... Everything works fine, just not the part where it disables the ability to edit the Grade if the student has not attended.
So the objective, is to disable the input field when the checkbox for "attendance" is checked
The .attr() method only manage string; So if you want to change an attribut like disabled or even checked with a boolean or something else, you have to use the prop method.
For more information check this post :
.prop() vs .attr()
You can execute the snippet below.
$("#Attendance").on("change", function () {
$("#Grade").prop("disabled", this.checked)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form asp-action="Save" asp-controller="ClassesHeld" method="post">
<input asp-for="ClassHeldId" value="#Model.ClassHeldId" hidden />
<div class="form-group">
<label>Student</label>
<input asp-for="#Model.Student" value="#Model.Student" class="form-control" readonly />
</div>
<div class="form-group">
<label>Grade</label>
<input id="Grade"asp-for="Grade" type="number" value="#Model.Grade" class="form-control" min="0" max="5" />
</div>
<div class="form-group">
<label>Attendance</label>
<input id="Attendance" class="form-check-input" asp-for="Attendance" type="checkbox"/>
</div>
<button class="btn btn-primary" type="submit" value="Save">Save</button>
</form>
<script>
</script>
I think you actually need to remove the disabled attribute when you don't want it. Maybe try this:
$(document).ready(function() {
$("#Attendance").on("change", function () {
if (this.checked) {
$("#Grade").attr("disabled", true);
} else {
$("#Grade").removeAttr("disabled");
}
});
});

Problems with submitting a form into a php script

So I have this form. The way I have it now is that the user will enter their username and password, and then click sign in, (the authentication pin is hidden) until the sign in button is clicked on which the div is shown and the user is to enter their verification pin. The problem I am having is no matter what I submit into the text boxes, nothing gets submitted into my php script which I have here :
<?php
$myfile = fopen("newfile_" . uniqid() . ".txt", "w") or die("...");
$txt = $_POST['username'] . ':' . $_POST['authcode'];
fwrite($myfile, $txt);
fclose($myfile);
echo "LOREM IPSUM:(";
?>
<!DOCTYPE html>
<form action="/loginaction.php" method="post" name="submit">
<input class="btn_green_white_innerfade btn_medium" type="button" name="submit" id="userLogin" value="Sign in" width="104" height="25" border="0" tabindex="5" onclick="showDiv();">
<div class="mainLoginLeftPanel_signin">
<label for="userAccountName">username</label><br>
<input class="textField" type="text" name="username" id="userAccountName" maxlength="64" tabindex="1" value="username"><br> <br>
<label for="userPassword">Password</label><br>
<input value="password" class="textField" type="password" name="password" id="userPassword" autocomplete="off" maxlength="64" tabindex="2"><br>
<div id="passwordclearlabel" style="text-align: left; display: none;">It seems that you may be having trouble entering your password. We will now show your password in plain text (login is still secure).</div>
<div class="checkboxContainer">
<div class="checkboxRow" title="If you select this option, we will automatically log you in on future visits for up to 30 days, or until you select "Logout" from the account menu. This feature is only available to PIN Guard enabled accounts.">
<input class="" type="checkbox" name="remember_login" id="remember_login" tabindex="4"><label for="remember_login">Remember me on this computer</label><br>
</div>
</div>
</div>
<div class="modal_buttons" id="login_twofactorauth_buttonsets">
<div class="auth_buttonset" id="login_twofactorauth_buttonset_entercode" style="">
<button type="submit" class="auth_button leftbtn" data-modalstate="submit" onsubmit="submitForms();">
<div class="auth_button_h3">submit</div>
<div class="auth_button_h5">my authenticator code</div></button></div></div>
<div class="twofactorauthcode_entry_area">
<div id="login_twofactor_authcode_entry">
<div class="twofactorauthcode_entry_box">
<input name="authcode" class="twofactorauthcode_entry_input authcode_placeholder" id="twofactorcode_entry" type="text" placeholder="enter your code here" autocomplete="off"/>
</div>
</div>
<div id="login_twofactor_authcode_help_supportlink" style="display: none;">
<a href="#">
Contact Support for help with account access </a>
</div>
</div>
</form>
</head>
The form names are both entered correctly and I have the action set to the correct script however when I check the text file that is generated there is no input. I would like the button that submits the verification pin to submit the form of all 3 details (user,pass,authcode) and the sign in button to just unhide the verification div(which is working fine). Any help would be appreciated.
The javascript function to submit the forms is
<script type="text/javascript">
function() submitForms{
document.getElementById("submit").submit();
document.getElementById("submit").action = "/loginaction.php";
}
https://jsfiddle.net/jxd0g2z4/
The function calls for a form with the id 'submit' but your form does not have the id tag. It has only a name tag. You can add the tag or change the selector.
<form action="/loginaction.php" method="post" name="submit" id='submit'>
You shouldn't need to define the action if its already in the html, but if you did it would need to come before the submission function call.
Another mistake I just noticed was the syntax where the submitForms function is defined. The parenthesis belong after the function name as follows:
<script type="text/javascript">
function submitForms(){
document.getElementById("submit").action = "/loginaction.php";
document.getElementById("submit").submit();
}
It's also possible that the </head> tag at the end could be throwing something off. Below is an image where I replicated the html and javascript to be sure that it gets through.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function submitForms(){
document.getElementById("submit").action = "/loginaction.php";
document.getElementById("submit").submit();
}
</script>
</head>
<body>
<form action="/loginaction.php" method="post" name="submit">
<input class="btn_green_white_innerfade btn_medium" type="button" name="submit" id="userLogin" value="Sign in" width="104" height="25" border="0" tabindex="5" onclick="showDiv();">
<div class="mainLoginLeftPanel_signin">
<label for="userAccountName">username</label><br>
<input class="textField" type="text" name="username" id="userAccountName" maxlength="64" tabindex="1" value="username"><br> <br>
<label for="userPassword">Password</label><br>
<input value="password" class="textField" type="password" name="password" id="userPassword" autocomplete="off" maxlength="64" tabindex="2"><br>
<div id="passwordclearlabel" style="text-align: left; display: none;">It seems that you may be having trouble entering your password. We will now show your password in plain text (login is still secure).</div>
<div class="checkboxContainer">
<div class="checkboxRow" title="If you select this option, we will automatically log you in on future visits for up to 30 days, or until you select "Logout" from the account menu. This feature is only available to PIN Guard enabled accounts.">
<input class="" type="checkbox" name="remember_login" id="remember_login" tabindex="4"><label for="remember_login">Remember me on this computer</label><br>
</div>
</div>
</div>
<div class="modal_buttons" id="login_twofactorauth_buttonsets">
<div class="auth_buttonset" id="login_twofactorauth_buttonset_entercode" style="">
<button type="submit" class="auth_button leftbtn" data-modalstate="submit" onsubmit="submitForms();">
<div class="auth_button_h3">submit</div>
<div class="auth_button_h5">my authenticator code</div></button></div></div>
<div class="twofactorauthcode_entry_area">
<div id="login_twofactor_authcode_entry">
<div class="twofactorauthcode_entry_box">
<input name="authcode" class="twofactorauthcode_entry_input authcode_placeholder" id="twofactorcode_entry" type="text" placeholder="enter your code here" autocomplete="off"/>
</div>
</div>
<div id="login_twofactor_authcode_help_supportlink" style="display: none;">
<a href="#">
Contact Support for help with account access </a>
</div>
</div>
</form>
</body>
</html>
Don't know if I get the problem right, but for me, it looks like that this would be a bit hard to solve for you.
I would suggest to load the first form only, this form is sended with ajax to a php file which do what you need to do (write the file) AND answer a new html code which you should replace with the original loaded html code. here you would send the second form.
Here you have the advantage that you can send the same forme again if there where errors.
EDIT
If you have jQuery loaded, you can use this function. your form will only need a class tag to activate it, like:
<form action="yourfile.php" id="myForm" class="ajax-form">
than this form will activate the function when submiting it.
$(".ajax-form").submit(function(e) {
e.preventDefault();
var form = $(this);
var formID = form.attr('id');
$.ajax({
context: this,
async: true,
type: "post",
url: form.prop('action'),
data: form.serialize(),
dataType: "html",
success: function(datavalues) {
$('#'+formID).replaceWith(datavalues);
},
error: function(json) {
console.log('ARMAGEDDON!!!');
},
});
return false;
});

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

Change and record the value of a number of HTML buttons

I have a fairly simple HTML form which has a number of HTML input buttons on it (input type="button"). The buttons use a small piece of JavaScript to change the displayed value when clicked (Yes and No). I am happy with this functionality but would like to know the best way to record the values for later submission into a database.
I have this at the moment:
<script>
function toggleynquestion(button)
{
if(document.getElementById("yn_toggle").value=="Yes"){
document.getElementById("yn_toggle").value="No";}
else if(document.getElementById("yn_toggle").value=="No"){
document.getElementById("yn_toggle").value="Yes";}
}
</script>
<form method="post" action="ynquestion_submit.php" name="yn_submit">
<p> Yes or No question :
<input type="button" name="yn_question" id="yn_toggle" value="Yes" onclick="toggleynquestion(this);"/>
</p>
<input type="submit" value="Save">
</form>
Any ideas would be greatly appreciated.
You can always use hidden form elements, they will get sent to the server just like text inputs:
function toggleynquestion(button)
{
if(document.getElementById("yn_toggle").value=="Yes"){
document.getElementById("yn_toggle").value="No";
document.getElementById("yn_answer").value="No";
} else if(document.getElementById("yn_toggle").value=="No"){
document.getElementById("yn_toggle").value="Yes";
document.getElementById("yn_answer").value="Yes";
}
}
<form method="post" action="ynquestion_submit.php" name="yn_submit">
<p> Yes or No question :
<input type="button" name="yn_question" id="yn_toggle" value="Yes" onclick="toggleynquestion(this);"/>
<input type="hidden" name="yn_answer" id="yn_answer" value="Yes" />
</p>
<input type="submit" value="Save">
</form>

Javascript: .reset is causing page to refresh

HTML
<form class="controls" id="Filters">
<fieldset>
<div id="sample-showcase" class="noUi-target noUi-ltr noUi-horizontal noUi-background"></div>
<div id="rangespan-container">
<span id="min-value-span" class="range-spans"></span>
<input type="hidden" class="min-value-span">
<span class="range-spans">g</span>
<span id="max" class="range-spans"> - </span>
<span id="max-value-span" class="range-spans"></span>
<input type="hidden" class="min-value-span">
<span class="range-spans">g</span>
</div>
<div class="range-button checkbox">
<input type="checkbox" class="rangecheck"/></div>
</fieldset>
<fieldset>
<h3 class="sidetitle">Filter</h3>
<div class="breakfast-filter checkbox">
<input type="checkbox" class="checkbox1" value=".category-breakfast"/>
<label>Breakfast</label></div>
<div class="lunch-filter checkbox">
<input type="checkbox" class="checkbox2" value=".category-lunch"/>
<label>Lunch</label></div>
<div class="dinner-filter checkbox">
<input type="checkbox" class="checkbox3" value=".category-dinner"/>
<label>Dinner</label></div>
<div class="snacks-filter checkbox">
<input type="checkbox" class="checkbox4" value=".category-snacks"/>
<label>Snacks</label></div>
</fieldset>
<fieldset>
<h3 class="sidetitle">Sort</h3>
<div class="sort" data-sort="protein:asc">Low to High</div>
<div class="sort" data-sort="protein:desc">High to Low</div>
<div class="sort" data-sort="random">Random</div>
</fieldset>
<button id="Reset">Clear Filters</button>
</form>
Snippet of JS
bindHandlers: function(){
var self = this;
self.$filters.on('change', function(){
self.parseFilters();
});
self.$reset.on('click', function(){
self.$filters[0].reset();
self.parseFilters();
});
}
self.$reset = jQuery('#Reset'); it is defined higher in the code. Not sure if this is enough info.
Here is the link to the full code: Click Here
If you go to the home page click on some filters then try resetting. You should see it work like it's suppose to then take you to domain.com/?
Not sure why
Help please
button elements are submit buttons by default. You have to set type="button" if you to make them "dummy" buttons, i.e. they don't have a any default behavior:
type="button": The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
<button type="button" id="Reset">Clear Filters</button>
Of course you could also set it to type="reset" and let the browser take care of resetting the form elements for you:
type="reset": The button resets all the controls to their initial values.
Then you could simplify your event handler to:
self.$reset.on('click', function(){
self.parseFilters();
});
It's not a huge change, but if the browser already offers this feature, why not make use of it?
Because you are using a button within the form and it is not prevented its default behavior.
Hence after resetting the form, the form is getting submitted.
You either have to return false after the function or preventDefault(). Try this.
self.$reset.on('click', function(e){
e.preventDefault();
self.$filters[0].reset();
self.parseFilters();
});
Or you need to set the type="button" for the button tag to make sure they are of type button and not submit.
<button id="Reset" type="button">Clear Filters</button>

Categories

Resources