I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I'd like to know which submit button was clicked without applying a .click() event to each one.
Here's the setup:
<html>
<head>
<title>jQuery research: forms</title>
<script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var me = event.currentTarget;
var data = me.data.value;
var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
</script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
<input type='hidden' name='data' value='blahdatayadda' />
<input type='submit' name='name1' value='value1' />
<input type='submit' name='name2' value='value2' />
</form>
</body>
</html>
Live example on jsfiddle
Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?
I asked this same question: How can I get the button that caused the submit from the form submit event?
I ended up coming up with this solution and it worked pretty well:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val();
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
In your case with multiple forms you may need to tweak this a bit but it should still apply
I found that this worked.
$(document).ready(function() {
$( "form" ).submit(function () {
// Get the submit button element
var btn = $(this).find("input[type=submit]:focus" );
});
}
This works for me:
$("form").submit(function() {
// Print the value of the button that was clicked
console.log($(document.activeElement).val());
}
When the form is submitted:
document.activeElement will give you the submit button that was clicked.
document.activeElement.getAttribute('value') will give you that button's value.
Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."
There is a native property, submitter, on the SubmitEvent interface.
Standard Web API:
var btnClicked = event.submitter;
jQuery:
var btnClicked = event.originalEvent.submitter;
Here's the approach that seems cleaner for my purposes.
First, for any and all forms:
$('form').click(function(event) {
$(this).data('clicked',$(event.target))
});
When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.
Then, in $('form').submit(), you can inquire what was last clicked, with something like
if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();
Wow, some solutions can get complicated! If you don't mind using a simple global, just take advantage of the fact that the input button click event fires first. One could further filter the $('input') selector for one of many forms by using $('#myForm input').
$(document).ready(function(){
var clkBtn = "";
$('input[type="submit"]').click(function(evt) {
clkBtn = evt.target.id;
});
$("#myForm").submit(function(evt) {
var btnID = clkBtn;
alert("form submitted; button id=" + btnID);
});
});
I have found the best solution is
$(document.activeElement).attr('id')
This not only works on inputs, but it also works on button tags.
Also it gets the id of the button.
Another possible solution is to add a hidden field in your form:
<input type="hidden" id="btaction"/>
Then in the ready function add functions to record what key was pressed:
$('form#myForm #btnSubmit').click(function() {
$('form#myForm #btaction').val(0);
});
$('form#myForm #btnSubmitAndSend').click(function() {
$('form#myForm #btaction').val(1);
});
$('form#myForm #btnDelete').click(function() {
$('form#myForm #btaction').val(2);
});
Now in the form submition handler read the hidden variable and decide based on it:
var act = $('form#myForm #btaction').val();
Building on what Stan and yann-h did but this one defaults to the first button. The beauty of this overall approach is that it picks up both the click and the enter key (even if the focus was not on the button. If you need to allow enter in the form, then just respond to this when a button is focused (i.e. Stan's answer). In my case, I wanted to allow enter to submit the form even if the user's current focus was on the text box.
I was also using a 'name' attribute rather than 'id' but this is the same approach.
var pressedButtonName =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
$(":input[type=submit]:first")[0].name :
$(":input[type=submit]:focus")[0].name;
This one worked for me
$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);
}
Here is my solution:
$('#form').submit(function(e){
console.log($('#'+e.originalEvent.submitter.id));
e.preventDefault();
});
If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:
$(document).ready(function(){
$('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var input = $(event.currentTarget);
var which_button = event.currentTarget.value;
var data = input.parents("form")[0].data.value;
// var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute
$(document).on('click', '[type=submit]', function() {
var form = $(this).prop('form') || $(this).closest('form')[0];
$(form.elements).filter('[type=submit]').removeAttr('clicked')
$(this).attr('clicked', true);
});
$('form').on('submit', function() {
var submitter = $(this.elements).filter('[clicked]');
})
You can simply get the event object when you submit the form. From that, get the submitter object. As below:
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
}
In case you want to send this form to the backend, you can create a new form element by new FormData() and set the key-value pair for which button was pressed, then access it in the backend. Something like this -
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let form = $(this);
let newForm = new FormData($(form)[0]);
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
if (submitter_btn.attr("name") == "approve_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else if (submitter_btn.attr("name") == "reject_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else {
console.log("there is some error!");
return;
}
}
I was basically trying to have a form where user can either approve or disapprove/ reject a product for further processes in a task.
My HTML form is something like this -
<form method="POST" action="{% url 'tasks:review-task' taskid=product.task_id.id %}"
class="review-form">
{% csrf_token %}
<input type="hidden" name="product_id" value="{{product.product_id}}" />
<input type="hidden" name="task_id" value="{{product.task_id_id}}" />
<button type="submit" name="approve_btn" class="btn btn-link" id="approve-btn">
<i class="fa fa-check" style="color: rgb(63, 245, 63);"></i>
</button>
<button type="submit" name="reject_btn" class="btn btn-link" id="reject-btn">
<i class="fa fa-times" style="color: red;"></i>
</button>
</form>
Let me know if you have any doubts.
Try this:
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){
// This is the ID of the clicked button
var clicked_button_id = event.originalEvent.submitter.id;
});
});
$("form input[type=submit]").click(function() {
$("<input />")
.attr('type', 'hidden')
.attr('name', $(this).attr('name'))
.attr('value', $(this).attr('value'))
.appendTo(this)
});
add hidden field
For me, the best solutions was this:
$(form).submit(function(e){
// Get the button that was clicked
var submit = $(this.id).context.activeElement;
// You can get its name like this
alert(submit.name)
// You can get its attributes like this too
alert($(submit).attr('class'))
});
Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.
$('form.form-js').submit(function(event){
var frm = $(this);
var btn = $(document.activeElement);
if(
btn.length &&
frm.has(btn) &&
btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
btn.is('[name]')
){
frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
}
// Handle the form submit here
$('#form-js-temp').remove();
});
Side note: I personally add the class form-js on all forms that are submitted via JavaScript.
Similar to Stan answer but :
if you have more than one button, you have to get only the
first button => [0]
if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId
$(document).on('submit', function(event) {
event.preventDefault();
var pressedButtonId =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
"myDefaultButtonId" :
$(":input[type=submit]:focus")[0].id;
...
}
This is the solution used by me and work very well:
// prevent enter key on some elements to prevent to submit the form
function stopRKey(evt) {
evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
var alloved_enter_on_type = ['textarea'];
if ((evt.keyCode == 13) && ((node.id == "") || ($.inArray(node.type, alloved_enter_on_type) < 0))) {
return false;
}
}
$(document).ready(function() {
document.onkeypress = stopRKey;
// catch the id of submit button and store-it to the form
$("form").each(function() {
var that = $(this);
// define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit,button", that).bind("click keypress", function(e) {
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
$("#form1").submit(function(e) {
var origin_id = $(e.target).data("callerid");
alert(origin_id);
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1" name="form1" action="" method="post">
<input type="text" name="text1" />
<input type="submit" id="button1" value="Submit1" name="button1" />
<button type="submit" id="button2" name="button2">
Submit2
</button>
<input type="submit" id="button3" value="Submit3" name="button3" />
</form>
This works for me to get the active button
var val = document.activeElement.textContent;
It helped me https://stackoverflow.com/a/17805011/1029257
Form submited only after submit button was clicked.
var theBtn = $(':focus');
if(theBtn.is(':submit'))
{
// ....
return true;
}
return false;
I was able to use jQuery originalEvent.submitter on Chrome with an ASP.Net Core web app:
My .cshtml form:
<div class="form-group" id="buttons_grp">
<button type="submit" name="submitButton" value="Approve" class="btn btn-success">Approve</button>
<button type="submit" name="submitButton" value="Reject" class="btn btn-danger">Reject</button>
<button type="submit" name="submitButton" value="Save" class="btn btn-primary">Save</button>
...
The jQuery submit handler:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function() {
...
// Ensure that we log an explanatory comment if "Reject"
$('#update_task_form').on('submit', function (e) {
let text = e.originalEvent.submitter.textContent;
if (text == "Reject") {
// Do stuff...
}
});
...
The jQuery Microsoft bundled with my ASP.Net Core environment is v3.3.1.
Let's say I have these "submit" buttons:
<button type="submit" name="submitButton" id="update" value="UpdateRecord" class="btn btn-primary">Update Record</button>
<button type="submit" name="submitButton" id="review_info" value="ReviewInfo" class="btn btn-warning sme_only">Review Info</button>
<button type="submit" name="submitButton" id="need_more_info" value="NeedMoreInfo" class="btn btn-warning sme_only">Need More Info</button>
And this "submit" event handler:
$('#my_form').on('submit', function (e) {
let x1 = $(this).find("input[type=submit]:focus");
let x2 = e.originalEvent.submitter.textContent;
Either expression works. If I click the first button, both "x1" and "x2" return Update Record.
I also made a solution, and it works quite well:
It uses jQuery and CSS
First, I made a quick CSS class, this can be embedded or in a seperate file.
<style type='text/css'>
.Clicked {
/*No Attributes*/
}
</style>
Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).
// Adds a CSS Class to the Button That Has Been Clicked.
$("form :input[type='submit']").click(function ()
{
if ($(this).hasClass("Clicked"))
{
$(this).removeClass("Clicked");
}
$(this).addClass("Clicked");
});
Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.
// On Form Submit
$("form").submit(function ()
{
// Test Which Button Has the Class
if ($("input[name='name1']").hasClass("Clicked"))
{
// Button 'name1' has been clicked.
}
else
{
// Button 'name2' has been clicked.
}
});
Hope this helps!
Cheers!
You can create input type="hidden" as holder for a button id information.
<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">
In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.
A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':
$("button").click(function() {
var id = $(this).attr('id');
...
});
Here is a sample, that uses this.form to get the correct form the submit is into, and data fields to store the last clicked/focused element. I also wrapped submit code inside a timeout to be sure click events happen before it is executed (some users reported in comments that on Chrome sometimes a click event is fired after a submit).
Works when navigating both with keys and with mouse/fingers without counting on browsers to send a click event on RETURN key (doesn't hurt though), I added an event handler for focus events for buttons and fields.
You might add buttons of type="submit" to the items that save themselves when clicked.
In the demo I set a red border to show the selected item and an alert that shows name and value/label.
Here is the FIDDLE
And here is the (same) code:
Javascript:
$("form").submit(function(e) {
e.preventDefault();
// Use this for rare/buggy cases when click event is sent after submit
setTimeout(function() {
var $this=$(this);
var lastFocus = $this.data("lastFocus");
var $defaultSubmit=null;
if(lastFocus) $defaultSubmit=$(lastFocus);
if(!$defaultSubmit || !$defaultSubmit.is("input[type=submit]")) {
// If for some reason we don't have a submit, find one (the first)
$defaultSubmit=$(this).find("input[type=submit]").first();
}
if($defaultSubmit) {
var submitName=$defaultSubmit.attr("name");
var submitLabel=$defaultSubmit.val();
// Just a demo, set hilite and alert
doSomethingWith($defaultSubmit);
setTimeout(function() {alert("Submitted "+submitName+": '"+submitLabel+"'")},1000);
} else {
// There were no submit in the form
}
}.bind(this),0);
});
$("form input").focus(function() {
$(this.form).data("lastFocus", this);
});
$("form input").click(function() {
$(this.form).data("lastFocus", this);
});
// Just a demo, setting hilite
function doSomethingWith($aSelectedEl) {
$aSelectedEl.css({"border":"4px solid red"});
setTimeout(function() { $aSelectedEl.removeAttr("style"); },1000);
}
DUMMY HTML:
<form>
<input type="text" name="testtextortexttest" value="Whatever you write, sir."/>
<input type="text" name="moretesttextormoretexttest" value="Whatever you write, again, sir."/>
<input type="submit" name="test1" value="Action 1"/>
<input type="submit" name="test2" value="Action 2"/>
<input type="submit" name="test3" value="Action 3"/>
<input type="submit" name="test4" value="Action 4"/>
<input type="submit" name="test5" value="Action 5"/>
</form>
DUMB CSS:
input {display:block}
I write this function that helps me
var PupulateFormData= function (elem) {
var arr = {};
$(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
arr[$(this).attr("name")] = $(this).val();
});
return arr;
};
and then Use
var data= PupulateFormData($("form"));
HTML code:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" <?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>/><br /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
This will make the checkbox stays checked, but when page is refresh or exit and comes back, the checkbox will be unchecked. Therefore, after some research, I tried the localStorage, but doesn't seem to quite figure it out yet.
localStorage code:
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {};
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
I have script tags around the localStorage code and after implementing these codes, my checkbox still doesn't stays checked.
Both code as a whole:
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" name="new_background"/>
</div>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function(){
$checkbox.each(function(){
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value){
$("#" + key).prop('checked', value);
});
</script>
<input type="submit" name="submit" value="Upgrade Background" class="button"/>
</form>
</div>
I would like to thank everyone that took time to help me figure out the solution to my question with the biggest thanks to #Pranav C Balan!!! Check out the finished code # http://stackoverflow.com/a/44321072/3037257
I think your code is executing before the form elements are loading, so place it at the end of your code or wrap it using document ready handler to execute only after the elements are loaded. If you were placed the code before the element $("#checkbox-container :checkbox") would select nothing since it is not yet loaded in the DOM.
One more thing to do, in your code the checkbox doesn't have any id so add a unique id to the element to make it work since the JSON is generating using the id value.
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
</script>
</div>
Working demo : FIDDLE
<script>
// document ready handler
// or $(document).ready(Function(){...
jQuery(function($) {
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
});
</script>
<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
<div id="checkbox-container">
Background Swap: <input type="checkbox" id="name" name="new_background" />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
</div>
Working demo : FIDDLE
An alternative to localStorage that only utilizes document.cookie:
$('input:checkbox').change(function() {
saveCookies();
});
To register the function and the actual function:
function saveCookies() {
var checkArray = [];
$('input.comic-check').each(function() {
if ($(this).is(':checked')) {
checkArray.push(1);
} else {
checkArray.push(0);
}
});
document.cookie = "checks=" + checkArray;
}
This is an alternative to localStorage, and depends on whether you want it to persist longer
And to retrieve the saved (on load)
var checks = getCookie("checks");
if (checks != "") {
checkArray = checks.split(',');
//unchecks boxes based on cookies
//also has backwards compatability provided we only append to the list in landing.ejs/generator.js
for (var i = 0; i < checkArray.length; i++) {
if (checkArray[i] == "0" && $('input.comic-check').length > i) {
var checkBox = $('input.comic-check')[i];
$(checkBox).prop('checked', false);
}
}
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Three situations you will need to check the checkbox
PHP have it set to checked="checked" (checked)
localStorage have it as true (checked)
all other situations this should be unchecked
all you need is to make sure first two situation you check the checkbox, then by default it is unchecked, but in your each you are also uncheck checkbox, therefore ignored the PHP part (as php set it to checked but localStorege set it to unchecked)
Example here: https://jsfiddle.net/dalinhuang/efwc7ejb/
//on page load
$.each(checkboxValue, function(key, value) {
if(value){
$("#" + key).prop('checked', value);
}
});
I would change:
<?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>
for:
<?php echo (isset($_POST['new_background']) && $_POST['new_background']=="on")? "checked" : "";?>
In inline HTML, you don't need the checked attribute to be checked=checked.
Just checked is enought.
checked=checked is used in JavaScript to programatically check a checkbox.
EDIT
About your localStorage...
I made an example for you on CodePen
//on page load, check the appropriate checkboxes.
var onloadChecks = JSON.parse(localStorage.getItem("checkboxValue"))
$.each(onloadChecks, function(key, value){
$("#" + key).prop('checked', value);
});
// ================ Saving checks
// Checkboxes collection.
var allCheckboxes = $("input[type='checkbox']");
// On change handler.
allCheckboxes.on("change", function() {
// Check how many checkboxes we have.
var jsonCheckboxes = {};
console.log("There is "+allCheckboxes.length+" checkboxes.");
// Building the json.
for(i=0;i<allCheckboxes.length;i++){
console.log(allCheckboxes.eq(i).attr("id"));
console.log(allCheckboxes.eq(i).is(":checked"));
jsonCheckboxes[allCheckboxes.eq(i).attr("id")] = allCheckboxes.eq(i).is(":checked");
}
console.log("jsonCheckboxes: "+JSON.stringify(jsonCheckboxes));
// Setting localStorage.
localStorage.setItem("checkboxValue", JSON.stringify(jsonCheckboxes));
console.log("LocalStorage: "+ localStorage.getItem("checkboxValue") );
});
Working around your comment : my goal is to find something that will make my checkbox stays checked if the user choose to, here's a way to have the localStorage handle it :
jQuery (3.2.1)
$(document).ready(function() {
var bground = localStorage.getItem('background'); // get the value if exists
if (bground == 'shadow') { // checkbox has been previously checked
$('#checker').attr('checked', 'checked');
}
if (bground == 'shadowless') { // checkbox has been previously unchecked
$('#checker').attr('');
}
$('#submit').submit(function() { // when form is submitted
bground = localStorage.getItem('background'); // get the value in LS
if($('#checker').is(':checked')) // is it checked or not ?
{ sh = 'shadow'; } else { sh = 'shadowless'; }
localStorage.setItem('background', sh); // update LS with new value
});
});
HTML (added id="submit" to form)
<form action="" id="submit" method="POST">
<div id="checkbox-container">
Shadowless background: <input type="checkbox" name="new_background" id="checker" /><br />
</div>
<input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>
This will make the checkbox stays checked, and when page is refreshed, the checkbox will be checked/unchecked depending on user's previous choice.
You could also use the jQuery change function instead of form submitting.
Just modify the line :
$('#submit').submit(function() { // comment/delete this line
// to the one below
// $('#checker').change(function() { // uncomment this line
I'm having trouble getting the match to bind to the oninput property of my text input. Basically I want my submit button to be enabled only when the regular expression is matched. If the regex isn't matched, a message should be displayed when the cursor is over the submit button. As it stands, typing abc doesn't enable the submit button as I want it to. Can anyone tell me what I'm doing wrong? Thank you.
<div id="message">
</div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt = $("#txt").value();
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
// disable buttons with custom jquery function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});
$('input[type="submit"]).disable(true);
var match = function(){
if (txt.match(PATTERN)){
$("#enter").disable(false)
}
else if ($("#enter").hover()){
function(){
$("#message").text(REQUIREMENTS);
}
}
</script>
Your code would be rewrite using plain/vanille JavaScript.
So your code is more clean and better performance:
<div id="message"></div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = false;
} else if (isHover(enter)) {
enter.disabled = true;
message.innerHTML = REQUIREMENTS;
} else {
enter.disabled = true;
}
}
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
</script>
If you wanted to say that you want handle the events in different moments, your code should be the following.
Note: the buttons when are disabled doesn't fired events so, the solution is wrapper in a div element which fired the events. Your code JavaScript is more simple, although the code HTML is a bit more dirty.
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<div style="display: inline-block; position: relative">
<input type="submit" id="enter" value="enter" disabled />
<div id="buttonMouseCatcher" onmouseover="showText(true)" onmouseout="showText(false)" style="position:absolute; z-index: 1;
top: 0px; bottom: 0px; left: 0px; right: 0px;">
</div>
</div>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = '';
} else {
enter.disabled = true;
}
}
function showText(option) {
message.innerHTML = option ? REQUIREMENTS : "";
}
</script>
Two problems here:
The variable txt is defined once outside the function match, so the value is fixed to whatever the input with id txt has when the script/page is loaded.
You should move var txt = $("#txt").val(); into the match function.
Notice I changed the function value() to val().
Problems identified:
jQuery events don't happen on disabled inputs: see Event on a disabled input
I can't fix jQuery, but I can simulate a disabled button without it actually being disabled. There's other hacks you could do to get around this as well, for example, by overlaying a transparent element which actually captures the hover event while the button is disabled.
Various syntactical errors: format your code and read the console messages
.hover()){ function() { ... } } is invalid. It should be .hover(function() { ... })
else doesn't need to be followed by an if if there's no condition
.hover( handlerIn, handlerOut ) actually takes 2 arguments, each of type Function
$('input[type="submit"]) is missing a close '
Problems identified by #Will
The jQuery function to get the value of selected input elements is val()
val() should be called each time since you want the latest updated value, not the value when the page first loaded
Design issues
You don't revalidate once you enable input. If I enter "abc" and then delete the "c", the submit button stays enabled
You never hide the help message after you're done hovering. It just stays there since you set the text but never remove it.
https://jsfiddle.net/Lh4r1qhv/12/
<div id="message" style="visibility: hidden;">valid entries must contain the string 'abc'</div>
<form method="POST">
<input type="text" id="txt" />
<input type="submit" id="enter" value="enter" style="color: grey;" />
</form>
<script>
var PATTERN = /abc/;
$("#enter").hover(
function() {
$("#message").css('visibility', $("#txt").val().match(PATTERN) ? 'hidden' : 'visible');
},
$.prototype.css.bind($("#message"), 'visibility', 'hidden')
);
$('form').submit(function() {
return !!$("#txt").val().match(PATTERN);
});
$('#txt').on('input', function() {
$("#enter").css('color', $("#txt").val().match(PATTERN) ? 'black' : 'grey');
});
</script>
I'm working on a page that is supposed to interact with the server via AJAX, but my experience with AJAX is extremely limited. Here's how the page is supposed to work.
When the button is clicked, if the "test" radio button is clicked, just display a pop up saying the input was valid.
When the button is clicked, if the "live" radio button is clicked, the program is supposed to send a request to the server using the URL "http://cs.sfasu.edu/rball/351/exam2.php" with the contents of the input box being the value for the "name" parameter.
The page will then send back a JSON object that I need to parse into a regular variable.
I'll leave the rest of the JSON stuff alone since that's not what I asked.
So far I have the design of the page done, but like I said I don't really know what I'm doing with the AJAX stuff. I have some code written for it, but not sure that it's right.
Here is my code:
<html>
<head>
<title>anner, Taylor</title>
<style type = "text/css">
canvas {
border: 2px solid black;
}
</style>
<script type = "text/javascript">
window.onload = function() {
var TTcanvas = document.getElementById("myCanvas");
var TTcontext = TTcanvas.getContext("2d");
TTcontext.strokeStyle = "red";
TTcontext.fillStyle = "red";
TTcontext.fillRect(250,50,100,100);
TTcontext.stroke();
TTcontext.beginPath();
TTcontext.moveTo(600, 0);
TTcontext.lineTo(0, 200);
TTcontext.lineWidth = 5;
TTcontext.strokeStyle = "black";
TTcontext.stroke();
}
function validate() {
var TTinput = document.getElementById("3letters").value;
if(TTinput.length < 3 || TTinput.length > 3) {
alert("Please enter 3 letters");
}
var TTtest = document.getElementById("test");
var TTlive = document.getElementById("live");
if(TTtest.checked == true) {
alert("Input is valid");
}
else if(TTlive.checked == true) {
return ajaxStuff();
}
}
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
var TTresponse = TTrequest.responseText;
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML.TTresponse;
}
}
}
</script>
</head>
<body>
<h1>Tanner, Taylor</h1>
<canvas id = "myCanvas" width = "600" height = "200"></canvas> <br>
<form>
Enter 3 letters: <input type="text" id="3letters"> <br>
<input type = "radio" id = "test" value = "test">Test
<input type = "radio" id = "live" value = "live">Live <br>
<input type = "button" id = "check" value = "Send" onclick="validate()">
</form>
<div id="myDiv">
</div>
</body>
</html>
And here is a link to my page on our server:
cs.sfasu.edu/cs351121/exam2.html
Also, I know it says exam, but this is actually just a review we were given for the actual exam that's next week. I'm just trying to figure out how this works but don't know what I'm doing wrong.
I'm not sure what the problem is. The code is correct
Ok now i get the problem. You are calling the request variable outside the scope. You are declaring the request variable inside your ajaxStuff function so its only accessible in that area. Thats why it is undefined. Try this:
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML=TTrequest.responseText;
}
}
}
to get the result just do this
TTrequest.send();
var response=TTrequest.responseText;
I know, I do not see the jQuery tag, but consider it if there are no framework restrictions.
Example:
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});
I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"