How to pass multiple variables from function to multiple jquery attr - javascript

This question is related to:
How to pass multiple variables from funtion to jquery attr
So the link above shows multiple solutions on how to pass multiple variables from a regular JavaScript function into multiple jQuery .attr() function values. But the question is, what if you want to send those variables to more than one jQuery functions?
That might sound strange as a statement, that's why I'll include an example.
$(function() {
function definingVars() {
var ValueOne = "Sucess with the value on input 1";
var IdOne = successWithTheId1;
var ClassOne = sucessWithTheClass1;
var ValueTwo = "Sucess with the value on input 2";
var IdTwo = successWithTheId2;
var ClassTwo = sucessWithTheClass2;
return [ValueOne, IdOne, ClassOne, ValueTwo, IdTwo, ClassTwo];
}
$("div:nth-child(1)").attr({
// var df = definingVars(); Incorrect syntax!!!
value: df.ValueOne,
id: df.IdOne,
class: df.ClassOne
})
$("div:nth-child(2)").attr({
// var df = definingVars(); Incorrect syntax!!!
value: df.ValueTwo,
id: df.IdTwo,
class: df.ClassTwo
})
});
input {
width: 20em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="noSucessWithTheId1" class="noSucessWithTheClass1" value="No sucess with the value on input 1">
<input type="text" id="noSucessWithTheId2" class="noSucessWithTheClass2" value="No sucess with the value on input 2">
</div>
Please don't ask about context. This is a dummy example.
$(function() {
function definingVars() {
var Value = "Sucess with the value";
var Id = successWithTheId;
var Class = sucessWithTheClass;
return {
value: Value,
id: Id,
class: Class
};
}
$("input").attr(definingVars())
});
This is one of the answers posted in the question related to this one. It looks beautiful, but it looks impossible to apply this same concept to the situation stated at the beginning of this question.

Not sure if that is what you want to do.
You missed the quotes on some string
I stored the attributes in an array
You should be targetting the input not the div
$(function() {
function definingVars() {
var ValueOne = "Sucess with the value on input 1";
var IdOne = "successWithTheId1";
var ClassOne = "sucessWithTheClass1";
var ValueTwo = "Sucess with the value on input 2";
var IdTwo = "successWithTheId2";
var ClassTwo = "sucessWithTheClass2";
return [{value:ValueOne, id:IdOne, class:ClassOne}, {value:ValueTwo, id:IdTwo, class:ClassTwo}];
}
var df = definingVars();
$("input:nth-child(1)").attr(df[0]);
$("input:nth-child(2)").attr(df[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="noSucessWithTheId1" class="noSucessWithTheClass1" value="No sucess with the value on input 1">
<input type="text" id="noSucessWithTheId2" class="noSucessWithTheClass2" value="No sucess with the value on input 2">
</div>

Changed the selector and returning an object instead of an array to simplify variables.
You can invoke the function and access the object property using the required key.
$(function() {
function definingVars() {
console.log("invoked definingVars");
return {
ValueOne: "Sucess with the value on input 1",
IdOne: "successWithTheId1",
ClassOne: "sucessWithTheClass",
ValueTwo: "Sucess with the value on input 2",
IdTwo: "successWithTheId2",
ClassTwo: "sucessWithTheClass2"
};
};
$($("div>input")[0]).attr({
value: definingVars()["ValueOne"],
id: definingVars()["IdOne"],
class: definingVars()["ClassOne"]
});
$($("div>input")[1]).attr({
value: definingVars()["ValueTwo"],
id: definingVars()["IdTwo"],
class: definingVars()["ClassTwo"]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="noSucessWithTheId1" class="noSucessWithTheClass1" value="No sucess with the value on input 1">
<input type="text" id="noSucessWithTheId2" class="noSucessWithTheClass2" value="No sucess with the value on input 2">
</div>

Related

If text box value matches then make that specific label text to yes else no

Iam trying check if the text of label matches with the text box if matches then make that specific label text to yes else no but in my code am not sure what is wrong but that is not happening for all it is showing "no" it self
Demo
HTML
<input class="master" value="1">
<label class="user_label" >1</label>
<label class="user_label" >0</label>
<label class="user_label" >1</label>
JS:
$(function() {
var master = $('input.master').get(0).value; // get the master value
var fn = function() {
return this.text === master ? "yes" : "noo";//if current text-box matches master,then yes else no
};
$('label.user_label').text(fn); // loop and replace text for each user input
});
this.text will be undefined inside fn, because this is a DOM node, and it doesn't have text property.
You can wrap it as a jQuery object and use the text() method:
var fn = function() {
return $(this).text() === master ? "yes" : "noo";
}
http://jsfiddle.net/L6d39f10/5/
You can simplify your code as follows, second parameter in text() callback function refers the old text value. You can use val() for getting value in jQuery.
var val = $('input.master').val();
$('.user_label').text(function(i, text){
return val === text ? 'yes' : 'no';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="master" value="1">
<label class="user_label">1</label>
<label class="user_label">0</label>
<label class="user_label">1</label>
when fn passed into $('label.user_label').text(fn) the context changed but still this.text is undefined. use this.textContent,this.innerHTML,$(this).text()
use text to compare and then modify it that makes logic odd, should it be like this?
$(function() {
$('input.master').keyup(function() {
var master = $(this).val(); // get the master value
var fn = function() {
return $(this).attr('data-val') === master ? "yes" : "noo"; //if current text-box matches master,then yes else no
};
$('label.user_label').text(fn); // loop and replace text for each user input
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="master" value="">
<label class="user_label" data-val="1"></label>
<label class="user_label" data-val="0"></label>
<label class="user_label" data-val="1"></label>
$(function() {
var master = $('input.master').get(0).value; // get the master value
$('label.user_label').each(function(){
if($(this).text() === master){
$(this).text("yes");
}else{
$(this).text("no");
}
});
});

possible to change one variable or another inside of a function

I don't know if this is possible so I figured this would be the place to ask.
I have two inputs and they each hold a unique value. They each have their own respective variable that the value is saved into. I was wondering if there was a way to use just one function to update their values instead of two seperate ones. Below is my code so far.
<form>
<input type="text" id="valueOne" onchange="changeValueOne(this.value)">
<input type="text" id="valueTwo" onchange="changeValueTwo(this.value)">
</form>
var valueOne = parseFloat($('#valueOne'));
var valueTwo = parseFloat($('#valueTwo'));
function changeValueOne(newValueOne) {
valueOne = newValueOne;
}
function changeValueTwo(newValueTwo) {
valueTwo = newValueTwo;
}
Try this:
var valueOne, valueTwo;
$("#valueOne, #valueTwo").change(function(){
if($(this).attr('id') == 'valueOne') {
valueOne = $(this).val();
} else {
valueTwo = $(this).val();
}
});
You could have a second parameter to indicate which variable to store and/or where.
var values;
function changeValue(newValue, pos){
values[pos] = newValue;
}
Change html to:
<input type="text" id="valueOne" onchange="changeValue(this.value, 'first')">
<input type="text" id="valueOne" onchange="changeValue(this.value, 'second')">
Alternatively if you want to store them in separate variables:
function changeValue(newValue, pos){
if(pos == 'first'){
valueOne = newValue;
} else if(pos == 'second'){
valueTwo = newValue;
}
}
the simple expandable way uses a collection instead of vars:
<form>
<input type="text" id="valueOne" onchange="changeValue(value, id)">
<input type="text" id="valueTwo" onchange="changeValue(value, id)">
</form>
<script>
var vals={
valueOne : parseFloat($('#valueOne').val()),
valueTwo : parseFloat($('#valueTwo').val())
};
function changeValue(newValue, slot) {
vals[slot] = newValue;
}
</script>
not only is it incredibly simple and fast, this lets you add many options without reworking the forking code (ifs), all you need to do is modify the vals object and the handler will keep up automatically with all available options, even creating new ones on-the-fly if needed (from new inputs being appended during run-time).

Set input value with JavaScript - depending on value of different input

Hey I got this problem I cannot work out by myself. It's html form which passes data to PHP to send mail.
First, I have dropdown list:
<select id="dropdown" name="dropdown">
<option selected="true" disabled="disabled">Choose</option>
<option id="A" value="one#gmail.com">One</option>
<option id="B" value="two#gmail.com">Two</option>
</select>
This dropdown defines the value of next input:
<input type='text' name="to" id="to" value="e-mail"/>
<script>
document.getElementById('dropdown').onchange = function () {
document.getElementById('to').value = event.target.value
}
</script>
At last, I need to define third input from the value of second.
<input type='text' name="from" id="from" value="Office manager"/>
But this last code doesn't work for me:
<script>
var name;
if (document.getElementById('to').value == "one#gmail.com" {
name = "Martin";
} else {
name = "Tom";
}
document.getElementById("from").value = name;
</script>
How do I proceed?
JSFiddle
It does if you put it like this
http://jsfiddle.net/170x1xs9/
document.getElementById('dropdown').onchange = function () {
document.getElementById('to').value = event.target.value
var name;
if (document.getElementById('to').value == "one#gmail.com") {
name = "Martin";
} else {
name = "Tom";
}
document.getElementById("from").value = name;
}
Syntax Error.
if (document.getElementById('to').value == "one#gmail.com" // No ')'
If you use event in your function, you should pass it as an argument.
document.getElementById('dropdown').onchange = function (event /* <-------- HERE */) {
document.getElementById('to').value = event.target.value
}
By not declaring it, you're using window.event, which might work in some browsers, but it's bad practise.
Check out the solution at: http://jsfiddle.net/jam7m5ca/1/
You forgot to pass the parameter event.
document.getElementById('dropdown').onchange = function (event) {
document.getElementById('to').value = event.target.value;
};

dynamic name for an input with jQuery

I have an issue with automatic name for input, I'll try to explain what i need to do. i have an id, that I get it from an external function. I need to use this numeric id to create another function like that.
var id = 10; // this is the id (from external function)
var value = "n"+bar.toString(); // (I try to cast the id as string)
$("input[name="+value+"]").on('change', function() { // use the cast value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
When I try to do that I get undefined, but when I change the id like that var id ="10" I get the correct answer, but I have a numeric input. Please help me figure out how to solve this problem.
Did you want something like this? This is based on an assumption that you have checkboxes within a form!
var ids = [10, 20, 30, 11, 12];
$.each(ids, function(index, val) {
var id = val;
var value = "n" + id; // `.toString` is not required!
$("#myForm").find("input[name='"+value+"']").on('change', function() {
if ($(this).is(":checked")) {
alert( $(this).val() );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" name="n10" value="10" />
<input type="checkbox" name="n11" value="11" />
<input type="checkbox" name="n12" value="12" />
</form>
use this code no need for id.toString()
var id = getId(); // this is the id (from externel function)
var value = "n" + id;
$("input[name="+value+"]").on('change', function() {
alert($("input[name="+value+"]:checked").val()); //change this selector accordingly
});
function getId() {
return 10;
}
here is the fiddle
https://jsfiddle.net/rrehan/srhjwrz4/
Try below code:
var id = 10; // this is the id (from externel function)
var value = id.toString(); // (i try to cast the id as string)
console.log(value);
$("input[name="+value+"]").on('change', function() { // use the casted value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
Demo Link

Looping through a form and populating from an object

I have a form and a javascript object.
<form id="myForm">
<input type="text" name="title">
<input type="text" name="image">
</form>
var myObject = {title: 'this is the title', image: 'image.jpg'}
Is there a way to run through the form inputs, and it any of the input names match the keys in the object, set the value?
Please note, I wish to run through the form and not the object, as the object has lots of other data in it which is not relevant to the form (not shown in example).
You can do:
$("#myForm input:text[name]").each(function() {
var name = $(this).attr("name");
for (var key in myObject) {
if (key == name) {
$(this).val(myObject[key])
break;
}
}
});
With this you don't ever loop the object, but you'll have to write an if-clause for every attribute:
var myObject = {title: 'this is the title', image: 'image.jpg'}
$('#myForm input').each(function()
{
if($(this).attr('name') === 'title')
{
$(this).val(myObject.title);
}
});

Categories