jQuery get submitted form values - javascript

I have 2 form and this forms have same input field (same names)
$("#first-form, #second-form").submit(function(event) {
$('#name').val()
});
In my example I get first form input value, I need to get submited form value.
I also trgu use $(this)('#name').val() but this method not work.
How to get submited form input values, if I have 2 same forms.

$('form').submit(function(event) {
$(this).find('[name=yourfieldsname]').val();
});
should do the trick.

$("#first-form, #second-form").submit(function(event) {
$('#'+$(this).attr('id')+' #name').val();
});

Once you've corrected the issue of (apparently) having duplicated IDs, you can select the input with a given name only inside the form that's been submitted like so:
$('form').submit(function() {
var name = $('[name="name"]', this).val();
});
Inside the submit event handler this refers to the form that triggered the event (i.e. the form being submitted), and $(selector, element) is equivalent to $(element).find(selector) which searches only inside of element for elements matching the selector.

Related

How do I clear a value stored in a form.submit function

The issue is when I attempt to resubmit a form without refreshing the page the event handler for the form submission retains the value for the previous submission.
The form contains a select element that is populated with options from an API. The selected option is used to make a request URL and get data from the API. When the form is submitted a second time without refreshing the form. Submit event handler constructs a URL with the previous value and then it constructs a URL with the newly selected value. I have tried to a reset on the form which does reset the select element to its initial state but it does not clear the previously selected value from the submit event handler.
<form id="myform">
<label for="input">Select dog breed!<label>
<select class="breeds"></select>
<input type="submit" value="Enter">
</form>
let $select = $(".breeds");
$select.append($(`<option>select breed</option>`))
for (var i=0; i<=breeds.length; i++){
$select.append($(`<option></option>`).text(breeds[i]).html(breeds[i]))
}
$('.breeds').on('change', function(){
console.log('on change running')
let breed = $(".breeds :selected").text()
console.log(`breed in on change: ${breed}`)
watchForm(breed)
})
function watchForm(breed) {
console.log(`watchForm running`)
console.log(`breed in watchform is: ${breed}`) //here breed logs as the value for first submission and then the second submission
$('form').submit(event => {
console.log(`breed in form submit is ${breed}`)
event.preventDefault();
//console.log(`num is ${num}`)
getDogImage(breed);
$('#myform').get(0).reset()
});
}
Best and simple solution ever
Use trigger()
$('#myform').trigger("reset");
You're good to go!!
You can use something like that. $('myform').val('');
Jquery selector can return one or more element, so it returns an array.
Since reset() is a Javascript function and we are forcefully using it in jquery, it requires a specific element to perform reset action.
$('#myform')[0].reset()
Using vanilla Javascript is the easiest and simplest one because id is unique in a HTML document.
document.getElementById("myForm").reset();

2 similar forms on the one page, $(this).find(); is getting value from the last form

I have 2 forms on 1 page. I am trying to get the value of the name field from the first form using jQuery but jQuery is always getting the name value from the 2nd form. The code looks like this:
$('#registration-form').each(function(){
var $this = $(this);
$this.submit(function (event) {
var firstName = $(this).find('input[name="firstName"]').val();
console.log(firstName);
});
});
Why is this code not working? Your help is much appreciated!
Firstly you're selecting by id attribute, so you cannot have more than one element with the same id. This is why only one is found. The each() is also redundant in this case.
If you want to group elements use a class instead, although note that the each() is still redundant as jQuery will loop over each selected element internally so you can just attach the submit event handler directly, like this:
$('.reg-form').submit(function (e) {
var firstName = $(this).find('input[name="firstName"]').val();
console.log(firstName);
});

How to assign value to unchecked checkboxes

I'm creating a form with multiple checkboxes and I want to value of the checked checkboxes to be "yes" and the value of unchecked checkboxes to be "no". The site I'm hosting my form on does not let me add the hidden field with the same name and a different value so I have to find script that will add the hidden checkbox on submission and include the value of "no". Currently, when I submit the form the unchecked boxes are recorded as undefined but for data purposes I need it to be filled with "no".
Here is what I found:
$(document).ready($("#foo").submit(
function() {
// Add an event listener on #foo submit action...
// For each unchecked checkbox on the form...
$(this).find($("input:checkbox:not(:checked)")).each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "no"); // or 'off', 'false', 'no', whatever
// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;
$(form).append(input);
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
));
Why is the script not working?
You need to check out the jQuery API documents
$(document).ready(function(){}); it takes function callback, which may not needed here.
$("#foo").submittakes function callback, which will be called right before the form is submitted.
No need to wrap selector in $.find
You need to figure out the context of this
The this in $(this).attr("name") is referring the input box
The this in $(this)[0].form is still the input box
I guess you are trying to get the reference of forms. You may use document.forms
You need to change the input with $(this). Within the .each function $(this) will refer to the checkbox itself.
It isn't normal to have severals input with same name you can put the value directly in checkbox
$(this).find($("input:checkbox:not(:checked)")).each(function(){
$(this).val($(this).is(':checked') ? "yes" : "no")
})
I was able to use this much simpler script. Works perfectly.
$('#foo').click(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','yes');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:'no'}));
}
});
});

How do I prevent form input data from being reset when I remove and re-append the form element?

I have a form that needs to be appended elsewhere in the DOM, and when that occurs all form inputs return to their original values. Is there a way to retain the form input values when the form element is removed and re-appended? I'm using jQuery and the append() function.
This is what worked for me:
Before the form element is cloned using .clone(true):
$('#MyForm :input').each(function() {
$(this).data('val',$(this).val());
});
After the cloned form element is append()'d:
$('#MySameFormSomewhereElseInTheDOM :input').each(function() {
$(this).val($(this).data('val'));
});

How to access element id and other attributes using jQuery?

I have JavaScript method which acts when a particular class (mcb) of forms are submitted:
function BindCloseMessage() {
$(".mcb").submit(function(event) {
alert("closing..."); //Here I want to get the id of form
event.preventDefault();
});
}
In place of alert call, I need to access the id of form whose submit is called. How can I do it? Even better will be the tip for accessing any attribute...
Thanks
the id of the form being submitted will be
this.id
or in jQuery
$(this).attr('id') //although why type the extra letters?
$(".mcb").submit(function(e){
e.preventDefault();
$(this).attr("id"); // Returns FORM ID
});
You can learn more about jQuery's attribute-methods at http://docs.jquery.com/Attributes

Categories