Pass name in jQuery form submission - javascript

I do not know why the following line will not function properly:
$('form[name="updateNetwork"]').unbind('submit').submit();
I can submit my form with
$("form").unbind('submit').submit();
However doing so will not pass the name attribute of the form which my backend code must identify in order to properly process the form submission. Any assistance would be greatly appreciated.
Thanks

It seems that you have only one form in your page, and that the only reason you're trying to select it with the name attribute in jQuery is so that jQuery will send the name of the form to the server.
Well, that won't work. Once you get a reference to your form via jQuery, it doesn not matter which selector you had used. If what you want is to send a name parameter to your backend code with the form name, use a hidden input inside the form:
<input type="hidden" name="form-name" value="updateNetwork" />
Then, you can get a reference to the form any way you want. The best one, as stated by #anvlasop, is to give your form an id attribute.
EDITED
You were creating the jQuery form object in a wrong way. If you have this:
<input type="submit" name="updateNetwork" />
then you can't do this:
$('form[name="updateNetwork"]).submit();
I assume that you're calling this method, submit(), inside the event handler of the submit event. Don't do that! What you should do, is to only canll preventDefault if there is an error in the validation, and let the form be sent otherwise:
//Never do this:
$('form').bind('submit', function(e) {
var valid;
//code to validate
e.preventDefault();
if (valid) $('form').unbind('submit').submit();
});
Do this:
$('form').bind('submit', function(e) {
var valid;
try {
//code to validate
} catch (error) {
valid = false;
}
if (!valid) e.preventDefault();
});
This also will prevent the sending of the form is there is an exception during validation.

You can give an id to your form. Try something like this html code:
<form id='form_id'>
//your form elements here...
</form>
Then, with jQuery you can have a reference to the form like this:
$("#form_id").unbind('submit').submit();

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();

How can i show a validationMessage (for an input element) programmatically without a Form?

Im not sure if this is possible without using a form.
But I would like the browser to render the validation errors.
Again, I am doing this programmatically without a form.
i.e. No Form tag, and no submitting. Just straight-up scripting.
Updated
I would like to validate input fields, such as:
<input value="123" maxlength="5"/>
<input value="hllo wrld" spellcheck="true"/>
If you wan't to validate that fields on page load without any additional submit/click event this can be possible solution :
$( document ).ready(function() {
$("#fieldDiv input").each(function() {
if(!isNaN(this.value)) {
alert(this.value + " is a valid number");
}
});
});
Idea is to traverse all input fields and perfom validation. You can use custom attributes to know what validation to use.

Ajax form submit after validating input elements

I have a form which collects some information using text boxes. Some text boxes have a strick pattern, e.g. few input boxes take only numbers.
I was able to add validation using pattern attribute of input field. http://www.w3schools.com/tags/att_input_pattern.asp
However, when user submits the form I need to do a ajax post request to a different end point. So, I think I have to make a call to preventDefault() method to prevent default form submit.
But when I call preventDefault(), it also disables validating input fields.
How can I achieve validating fields and make a ajax request, only if the input fields pass the validation.
You can either way use this:
First change the input[type="submit"] to this:
<button onclick="submitThis()">Save</button>
function submitThis() {
var firstInput = $("#idoffirstinput).val(); // basic validation
if(firstInput == "correctinput") {
$.ajax({
// send the ajax form
})
}
}
You can seperately validate each input using the technique provided there, or the one I provided. The jQuery error will be same; I mean the validation.
Use this:
if(firstInput == "correctinput") {
// ajax form
} else {
// show the error popup!
}
The plus point for this one is that you can style the error dialouge popup too. Like
$("#errordiv").css("border", "1px solid #hexcode");
And everything else is same!
HTML and jQuery:
<form id="details">
Phone no: <input type="text" id="phone_no" pattern="[A-Za-z]{3}">
<input type="submit" id="submit">
</form>
var input = $('#phone_no').val();
if(input != '')
{
var YOUR_URL = 'www.example.com';
var formData = $('#details').serialize();// If you want to pass that data to that URL
$.post(YOUR_URL,formData,function(result){
});
}
else
{
return false;
}

Retrieving value of form fields in Jquery

I have a form field in html that goes along the lines of:
<form id="tasklist">
<input type="text" id="name" ...></input>
... more form elements here ...
</form>
Now in my jQuery code, I would like to get the value of these form elements, but I am unable to see what I'm doing wrong with the following code:
$(document).ready(function(){
$("#tasklist").submit(function(){
alert($("#name").val()); // This does not alert anything on form submit
});
});
I have made sure all of my html id's are unique, the javascript code is placed at the bottom of the document, in script tags and any other alert placed there works (i.e. alert("hello world"); place before the submit method.
I have seen a few other questions like this on stackoverflow, i.e. (Jquery form field value and Retrieving the Value of an input text field in Jquery) but they do not seem to solve my problem.
Any ideas?
When a form is submitted, the page reloads. You need to prevent that!
$(document).ready(function(){
$("#tasklist").on('submit', function(e){
e.preventDefault();
alert( $("#name").val() );
});
});
And close the functions properly!
You have some typos : the functions are not closed. It cause JS errors and could stop the script execution.
Try :
$(document).ready(function(){
$("#tasklist").submit(function(){
alert($("#name").val()); // This does not alert anything on form submit
});
});
Update
Basic fiddle exemple : http://jsfiddle.net/UQTY2/28/

Adding submit event on form prevents submit parameter from being included in HTTP POST

Just what the question title says. I'm using SpringMVC, but that's irrelevant really. I just need to be able to pass the submit button name=value along with the rest of the form parameters for validation and control purposes. Example below for clarification:
The HTML I'm using:
<form action='somepage.htm' method='post'>
<input name='somename' value='bob' />
<input type='submit' name='mybutton' value='click me' />
</form>
The JavaScript (with jQuery) I'm using:
$('form').submit(function() {
$('input[type="submit"]', this).attr('disabled','disabled');
return true;
}
And so the HTTP POST request looks like this without the JavaScript event binding:
somepage.htm?somename=bob&mybutton=click%20me
And with the bound event, it excludes the button parameter as such:
somepage.htm?somename=bob
I need to be able to disable the buttons and still send the button value to the server for processing.
Thanks!
SOLUTION:
The code I actually used to solve this problem is:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var clone = $(this).clone();
$(clone).attr("type","hidden");
$(this).attr('disabled','disabled');
$(clone).appendTo($(this).parents('form')[0]);
return true;
});
});
And in case anyone was wondering, pressing Enter on a field in the form does in fact trigger the click event on the first submit button in the form!
Disabled inputs cannot be submitted.
http://www.w3.org/TR/html4/interact/forms.html#h-17.12
So maybe the way to go is to add a hidden element <input type='hidden' value='foo' name='bar'/> to stimulate the validation methods on the other end.
I think, if the submit button is clicked, then it's values will also be submitted, like rest of the form.

Categories