Getting DOM element value using pure JavaScript - javascript

Is there any difference between these solutions?
Solution 1:
function doSomething(id, value) {
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id, this.value)" />
...and Solution 2:
function doSomething(id) {
var value = document.getElementById(id).value;
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id)" />

Update: The question was edited. Both of the solutions are now equivalent.
Original answer
Yes, most notably! I don't think the second one will work (and if it does, not very portably). The first one should be OK.
// HTML:
<input id="theId" value="test" onclick="doSomething(this)" />
// JavaScript:
function(elem){
var value = elem.value;
var id = elem.id;
...
}
This should also work.

The second function should have:
var value = document.getElementById(id).value;
Then they are basically the same function.

In the second version, you're passing the String returned from this.id. Not the element itself.
So id.value won't give you what you want.
You would need to pass the element with this.
doSomething(this)
then:
function(el){
var value = el.value;
...
}
Note: In some browsers, the second one would work if you did:
window[id].value
because element IDs are a global property, but this is not safe.
It makes the most sense to just pass the element with this instead of fetching it again with its ID.

Pass the object:
doSomething(this)
You can get all data from object:
function(obj){
var value = obj.value;
var id = obj.id;
}
Or pass the id only:
doSomething(this.id)
Get the object and after that value:
function(id){
var value = document.getElementById(id).value;
}

There is no difference if we look on effect - value will be the same. However there is something more...
Solution 3:
function doSomething() {
console.log( theId.value );
}
<input id="theId" value="test" onclick="doSomething()" />
if DOM element has id then you can use it in js directly

This should also work.
function doSomething() {
yourElement = document.getElementById("yourID);
yourValue = yourElement.value; console.log(yourValue);
console.log(yourValue);
}
<div id="yourID" value="1" onclick="doSomething()">
</div>
function doSomething() {
console.log( theId.value );
}
<input id="theId" value="test" onclick="doSomething()" />

Related

how to remember inputs value by using local storage?

I have tried to use local storage to remember the input's value after refreshing page. but my code does not work.
here is the HTML code
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>
and here is javascript
<script type="text/javascript">
var nameArr = ["name"];
var inputs = document.getElementsByName('name');
inputs.forEach(function(el){
el.value = getSavedValue(el);
})
function saveValue(e) {
var name = e.target.name;
var val = e.target.value;
localStorage.setItem(name, val);
}
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}
</script>
if there is a way to solve this problem please tell me.
and if there is a way to do that with jquery I will be thankful to tell me that.
Here are couple of things. First instead of onkeyup use onblur so value will be saved in storage only when the focus is removed from the element.
Secondly use a common class inputs in this case and give separate name to each element.
Then get all the elements with same class, iterate through it and get value of name property using getAttribute. Use this value to check if there exist a key in localStorage
var nameArr = ["name"];
var inputs = [...document.getElementsByClassName('inputs')];
inputs.forEach(function(el) {
console.log()
el.value = getSavedValue(el.getAttribute('name'));
})
function saveValue(e) {
var name = e.target.name;
var val = e.target.value;
localStorage.setItem(name, val);
}
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}
<input type="text" class='inputs' name="firstName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="lastName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="age" onblur="saveValue(event)" />
On your code you are passing the input object as a parameter instead of its name (or value; you choose). As localStorage only stores String key-value pairs, it won't work as you're trying to find a key that is an object.
in the forEach instead of:
el.value = getSavedValue(el);
set:
el.value = getSavedValue(el.name);
or let the "getSavedValue" function accept an object as parameter, but to access localStorage you must pass a string as the key.

How to create objects from multiple selectors in jquery?

I have two elements(#list1, #list2 in html). I need to create object and populate it from these two elements.
For example:
$('#list1, #list2').each(function(index,value){
var object =[ {#list1.value, #list2.value} ];
})
Something like that. So it can add these elements to array with each iteration. How it can be done?
it is .val()
you can push OR you can map
You can use a class so you do not need to list
NOTE: If there is no value attribute on the field, using this.getAttribute("value") on the .get examples will result in any field without value attribute to be omitted from the array instead of adding an empty value (Thanks #adz5A)
http://jsfiddle.net/mplungjan/jLsa80m9/7/
var object1 = [];
$('#list1, #list2').each(function() {
object1.push($(this).val())
})
console.log(object1);
// Smarter:
var object2 = $('#list1, #list2')
.map(function(index,$list) {
return $list.value; // or this.value or $(this).val();
})
.get();
console.log(object2);
// EVEN Smarter:
var object3 = $('.list')
.map(function() {
return this.value;
})
.get();
console.log(object3);
// The two following versions were posted by #rmn - I include them here for
// completeness sake. Upvote his answer if you like them
// ES6 with jQuery
var object4 = $('#list1, #list2').get().map(el => el.value)
console.log(object4);
// ES6 without jQuery
var object5 = [...document.querySelectorAll('#list1, #list2')].map(el => el.value)
console.log(object5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="value1" id="list1" class="list" />
<input type="text" value="value2" id="list2" class="list" />
I think you are looking for .get(). It returns as an array the set of matched DOM elements. You can easily combined this with map to retrieve the value of some attribute for instance
$("selector").map(function () { return this.getAttribute("value"); }).get();
Will get you the value attribute for the selection into an array. Note that you can use arrow function inside map as the second argument is the dom node itself, in my example the dom element is bounded to the lexical context this.
With jQuery
$('#list1, #list2').get().map(el => el.value)
Without jQuery
[...document.querySelectorAll('#list1, #list2')].map(el => el.value)
you can create array outside the loop and push it on each iteration
var object =[];
$('#list1, #list2').each(function(){
object.push($(this).val());
});
If you want to have id in your object, this is better:
function getList(){
var list = []
$("#input1, #input2").each(function(){
list.push({id: this.id, value: this.value });
});
console.log(list);
/*
OUTPUT:
[
{
"id": "input1",
"value": "v1"
},
{
"id": "input2",
"value": "v2"
}
] */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1" type="text" value="v1" />
<input id="input2" type="text" value="v2" />
<input type="button" onclick="getList()" value="get list" />

Get id of an element through a function

I have a function that is called in an onclick event in a checkbox field.
<input type='checkbox' checked='' onclick='return changeEnable();' id='someid'>
and the function
function changeEnable()
{
var val = $(this).attr('id');
alert(val);
}
I have that but it returns undefined. Is my syntax wrong or did I miss something?
Those checkboxes are dynamically created and have different id's, that's why I want to get the id for some task.
Note that this in your changeEnable function will be the window. You need to pass the reference to the element as a parameter to the function:
<input type='checkbox' checked='' onclick='return changeEnable(this);' id='someid'>
function changeEnable(el) {
var val = el.id
alert(val);
}
Or, as an improvement, use Javascript to attach your events for a better separation of concerns:
<input type="checkbox" id="someid">
$(function() {
$('#someid').change(function() {
var val = this.id
alert(val);
}
});
Note that the above uses the change event of the checkbox, which is better for accessibility reasons.
i think this code will help u a lot
<input type='checkbox' checked='' onclick='return changeEnable(this);' id='someid'>`
function changeEnable(thisobj)
{
var val = thisobj.id;
alert(val);
}
Also you should be aware of .call method which throws input context to function.
<input type='checkbox' checked='' onclick='changeEnable.call(this);' id='someid'>
function changeEnable()
{
var val = this.id;
alert(val);
}
use in this way:
<input type='checkbox' checked='' onclick='changeEnable(this);' id='someid'>
function changeEnable(el)
{
var val = el.id;
alert(val);
}

Define one function for multiple events

I originally defined the same function three times for three input fields like this:
var inputQ = document.getElementById("quantity");
var inputC = document.getElementById("compid");
var inputR = document.getElementById("quantreq");
inputQ.onkeypress = function() {
//code
}
inputC.onkeypress = function() {
//same code
}
inputR.onkeypress = function() {
//same code
}
But figured out it still works if shortened to:
inputQ.onkeypress = inputC.onkeypress = inputR.onkeypress = function() {
//code
}
Will this produce any unexpected effects? And is there perchance an even shorter way of doing it, something like ('#inputQ, #inputC, #inputR) = function() {}?
Thanks!
This will work just fine (a function is just an object like any other, so you can chain assignations).
If you want a shorter way, use jQuery:
$("#quantity, #compid, #quantireq").on("keypress", function() {
// code
});
If you wanted it to be more generic and not specify IDs everytime and without jquery you could assign each thing you need to validate/check with a class then just do something like...
<input id="quantity" type="text" val="0" class="check" />
<input id="compid" type="text" val="1" class="check" />
<input id="reqid" type="text" val="2" class="check" />
<script>
function notify(){
alert( "Here" );
}
[].slice.call( document.querySelectorAll( ".check" ) ).forEach( function(){
this.addEventListener( 'keypress' , notify, false);
});
</script>
This is for browsers that support forEach and querySelectorAll of course.

I can't use val()?

I'm having a problem with getting the val of an input element I have.
You see, I don't know if my code is wrong, but my Visual Studio (legal) doesn't even try to help me complete what I want to type. All it gives me is Value() and ValueOf().
The part of the code I'm using:
JS:
$(document).ready(start);
{
$("#b1").click(toev);
}
function toev() {
var value = $("#b1").val();
$("#output").append(value);
};
HTML:
<input type="text" id="output"/>
<td><input type="button" id="b1" value="1" /></td>
Demo http://jsfiddle.net/yS8tw/
Few things to note:
Use of document.ready
Use of Val
Also I like this appendVal function: http://jsfiddle.net/5R7eZ/ - Is it possible to do ".value +=" in JQuery?
Rest should fit the needs :)
code
$(document).ready(function(){
$("#b1").click(toev);
});
function toev() {
var value = $("#b1").val();
alert(value);
$("#output").val(value);
}
With AppendVal
$(document).ready(function(){
$("#b1").click(toev);
});
function toev() {
var value = $("#b1").val();
$("#output").appendVal(value);
}
$.fn.appendVal = function (newPart) {
return this.each(function(){ this.value += newPart; });
};
You can't append content to an <input> element because it cannot have content. Perhaps you meant
$('#output').val(value);
to set its value.

Categories

Resources