How to reach the element itself inside jQuery’s `val`? - javascript

My code is the following:
const pagedata = {
name: "Value for name",
email: "Value for email",
};
$(".fillvalfromvar").val(pagedata[$(this).attr("id")]);
I need to fill all the elements having the fillvalfromvar class with the value of the variable pointed to by the element id. For example the HTML is the following:
<input id="name" class="fillvalfromvar" type="text">
<input id="email" class="fillvalfromvar" type="text">
And I’d like to fill those vals with pagedata["name"] and pagedata["email"], respectively.
But the this value isn’t pointing to the original element. What should I use instead?

Use the syntax that accepts a function as the parameter
$('.fillvalfromvar').val( function(){
return pagedata[ this.id ];
});
(assuming that those input elements have the fillvalfromvar class)
or you could use the .each() method
$('.fillvalfromvar').each( function(){
this.value = pagedata[ this.id ];
});

simply use $.each
$('.fillvalfromvar').each(function(){
$(this).val(pagedata[$(this).attr('id')]);
});
or use $('input[id]') if those inputs dont have the class mentioned

Try this
$('.fillvalfromvar').each(function(){
$(this).val(pagedata[$(this).attr('id')]);
})

you need to define the class of your input text:
<input id='name' type='text' class="fillvalfromvar">
<input id='email' type='text' class="fillvalfromvar">
Please try this.

Related

Selecting specific element within a div?

I am building a contact form, and I am having problems with jQuery. I want to select specific input fields that have an error and apply the class err. Unfortunately, my code selects all inputs when there is an error. I am having trouble identifying which part of my logic is wrong.
$('#send_mail').click(function(){
$("#contact_body").find('label').each(function(){
var contact_label = $('input[required=true], textarea[required=true]');
var label_check = $(this).find(contact_label);
$(contact_label).removeClass('err');
if (!$.trim($(label_check).val())){
$(contact_label).addClass('err');
}
});
});
The order of my HTML goes something like so:
#contact_body
<label>
<input>
</label>
This selects all input and textarea elements:
var contact_label = $('input[required=true], textarea[required=true]');
Instead, you should restrict it to the elements within the label:
var contact_label = $(this).find('input[required=true], textarea[required=true]');
Note that $(contact_label) and contact_label are equivalent in your code, as well as $(label_check) and label_check.
Also, you can use the state parameter of toggleClass() to simplify this:
contact_label.removeClass('err');
if (!$.trim(label_check.val())){
contact_label.addClass('err');
}
… to this:
contact_label.toggleClass('err', !$.trim(label_check.val()));
Here's the updated event:
$('#send_mail').click(function(){
$('#contact_body').find('label').each(function(){
var contact_label = $(this).find('input[required=true], textarea[required=true]');
var label_check = $(this).find(contact_label);
contact_label.toggleClass('err', !$.trim(label_check.val()));
});
});
I think your original code would work if you just changed this line:
$(contact_label).addClass('err');
To this:
$(label_check).addClass('err');
Because $(contact_label) references all the required inputs, whereas $(label_check) references only the input being checked.
But your code could be simplified, and you make unnecessary calls to $(), giving it an argument that is already a JQuery object.
I also do not see that you need to loop through the labels. You could loop through the required inputs instead.
$('#send_mail').click(function(){
$("#contact_body").find(':input[required]').each(function() {
var $input = $(this);
$input.removeClass('err');
if (!$.trim($input.val())){
$input.addClass('err');
}
});
});
Which could be shortened by using the .toggleClass() function:
$('#send_mail').click(function(){
$("#contact_body").find(':input[required]').each(function() {
$(this).toggleClass('err', !$.trim($input.val()));
});
});
Notes:
The selector ':input' matches <input>, <select> and <textarea> elements.
This is a slightly different approach. Gives a bit more flexibility.
arr = ['first', 'last', 'email', 'msg']; //IDs of fields to check
$('#send_mail').click(function(){
$('input, textarea').removeClass('err');
for (var i=0; i<arr.length-1; i++) { //Loop through all field IDs
if ( $('#'+arr[i]).val() == '' ) {
$('#'+arr[i]).addClass('err').focus();
return false;
}
}
//AJAX to send email goes here
alert('Email sent');
});
.err{background:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="first">First Name:</label>
<input id="first" type="text" required /><br>
<label for="last">Last Name:</label>
<input id="last" type="text" required/><br>
<label for="email">Email:</label>
<input id="email" type="email" required /><br>
<label for="msg">Message:</label>
<textarea id="msg" required></textarea>
<button id="send_mail">Send</button>
you can simplify the code, there will be less mistakes:
$('#send_mail').click(function(){
$("#contact_body").find('label').each(function(){
var field = $(this).find('[required=true]');
if ($.trim($(field).val())){
$(this).removeClass('err');
}
});
});

What is the best way to iterate input inside a div using this

i'm trying to know (without success), what is the best way to iterate all input element with a specific class in a specific div after a click on a button.
<div>
<input type="text" class="inputtext">
<input type="text" class="inputtext">
<input type="text" class="inputtext">
<input type="text" class="anotherclass">
<input type="text" class="anotherclass">
<button class="full">click me</button>
</div>
So i want to get the value of every input with the class inputtext (but not the one with the class anotherclass). I've tried this :
$(".full").click(function() {
console.log($(this).parent().children(".inputtext").val());
});
Thanks for your attention !
Use .map
var values = $(".inputtext").map(function() { return this.value }).get();
values will be an array of each input value.
Use the .each method of JQuery:
$(".full").click(function() {
$(this).parent().children(".inputtext").each(function(){console.log($(this).val());});
});
Working Fiddle: https://jsfiddle.net/jx6d4neh/
Try with
$(".full").click(function() {
$(this).siblings(".inputtext").each(function(){
console.log($(this).val());
});
});
You could use the each() function, somewhat like this:
$(".full").click(function() {
$(this).parent().children(".inputtext").each(function(){
console.log($(this).val());
});
});
https://api.jquery.com/each/
Or better traverse using siblings() instead of parent().children() like this
$(".full").click(function() {
$(this).siblings(".inputtext").each(function(){
console.log($(this).val());
});
});
https://api.jquery.com/siblings/

form input element arrays with mootools

I tried searching for the answer to this, but did not find the specific answer I was looking for. In mootools, how do I access a form input element like below that has an array name using the "double dollar" ($$) function to be able to iterate through for form validation.
<input name="field[inventory_id]" type="text" />
<input name="field[asset_tag]" type="text" />
<input name="field[idea_tag] type="text" />
<input name="field[equip_make]" type="text" />
<input name="field[equip_model]" type="text" />
etc...
Thanks
Dan B
In MooTools you can use for example:
$$('input[name^="field"]')
This will get you all the input elements that have a name attribute starting with "field".
You could combine with that a .filter() with a funcion for validating and check in the end `the length property of this elements collection. Something like:
$$('button').addEvent('click', function () {
var inputs = $$('[name^="field"]');
var notValidating = inputs.filter(function (input) {
return !input.value;
})
alert('There are ' + notValidating.length + ' inputs not validating.');
});
jsFiddle: http://jsfiddle.net/kthaqmL2/
So I worked on this for a bit and came to the conclusion that giving all of the input elements a classname was the best method. I then used mootools double dollar function to iterate over all of the items with that classname.

pass a value from javascript to html

I have a hidden field
<input type="hidden" name="smname" />
Now i have a function in a js file count(); How can I assign the return value to the hidden field?
You could give your hidden field an unique id:
<input type="hidden" name="smname" id="smname" />
and then in javascript:
document.getElementById('smname').value = count();
where count is the function you want to invoke and which returns the value:
var count = function() {
return 'some value';
};
Try:
document.getElementsByName('smname')[0].value = count();
You want to use code such as
document.getElementById("name")
then deal with it as an object. remember to define a name/id for your html element.
If you give the input element an id attribute you will be able to get a reference to it in javascript using the document.getElementById() method then set the value property of the element
HTML
<input id="surname" type="hidden" name="smname" />
Javascript
var input = document.getElementById("surname");
input.value = count();

Using Javascript to change a value in a textbox

<input id="NameAjax" class="ac_input" type="text" value="">
And using jquery:
).click(function(e) {
document.getElementById("NameAjax").value = 1;
}
But after the click the value does not change:
<input id="NameAjax" class="ac_input" type="text" value="">
I am looking for the output to look exactly like:
<input id="NameAjax" class="ac_input" type="text" value="1">
How to fix it ?
$("#elementID").on('click', function() {
$("#NameAjax").val('1');
});
You mentioned Jquery so I am going to assume you are using it. If so try this:
$('#NameAjax').attr('value','1')
The first part $('#NameAjax') selects the input and the second attr('value','1') sets the value attribute to 1
Use the val method:
$('#NameAjax').val('1');
Don't use jquery only half the way. And don't use attr function to set a value.
$("element_idOrclass").click(function() {
$("#NameAjax").attr("value","1");
}

Categories