How to access element id and other attributes using jQuery? - javascript

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

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

jQuery get submitted form values

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.

Pass name in jQuery form submission

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

jQuery input value not working

Have looked for a solution to this but not found one.
$(document).ready(function() {
if ($("input").value()) {
$("h1").hide();
}
}
So this does not seem to be working ( $("h1").hide() is just a placeholder action... that part is not important, the problem is that the if statement is not working).
There is one form on the page, <input type=text>. I want to make it so that at all times, if there is any text in the input box a certain state is applied. If the input box returns to empty then the state is removed.
There are quite a few other functions inside the $(document).ready function which I omitted due to clarity... but as far as the scope of where the if statement lies it is directly inside of the document.ready function. P.S. The form is shown and hidden dynamically, but it is hard coded -- it is not being created dynamically.
What is wrong with where I have this if statement located?
Try with .val() like
$(document).ready(function(){
if ($("input").val()) {
$("h1").hide();
}
});
Better you use either name or id or class names as selectors.Because input can be of any number and they also includes checkboxes,radio buttons and button types
In jQuery you have to use .val() method and not .value(). Your check should be as follows:
if ($("input").val()) {
$("h1").hide();
}
Unlike .value() in JS, ther's .val() in JQuery.
$(document).ready(function() {
if ($("input").value()) {
$("h1").hide();
}
});
You should use keyup to know when a key is added/removed from the textbox
$(document).ready(function() {
$("#input_data").keyup(function() {
var dInput = $(this).val();
alert(dInput);
});
});
DEMO
NOTE: Since input can be of any number and checkboxes, radio buttons and button types all are included within the HTML input tag, You should use either name or id or class names as **selectors**.
input[type=text]
or, to restrict to text inputs inside forms
form input[type=text]
or, to restrict further to a certain form, assuming it has id myForm
#myForm input[type=text]
If You want a multiple attribute selector
$("input[type='checkbox'][name='ProductCode']")
//assuming input type as checkbox and name of that input being ProductCode
.value() is invalid. You should use .val() instead of .value(). Hope it will make it work?
You should use val at the place of value and the solution is :
$(document).ready(function() {
if ($("input").val()) {
$("h1").hide();
}
});

Categories