Get the element name attribute in JavaScript - javascript

How can I get the element name attribute in JavaScript?
HTML :
<input class="so" name="Name" value="bob"></input>
<input class="so" name="LastName" value="Feyzi"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input type="submit"></input>
JavaScript :
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
var elname = document.getElementByClassName('.so')[i].getAttribute('name');
//var eln = document.getElementsByTagName("input")[i].getAttribute("name");
var vala = document.querySelectorAll('.so')[i].value;
//alert(vala);
alert(elname);
}
After I run the script I want the person object to be set with this data:
person {
Name: "bob",
LastName: "Feyzi",
Email: "",
Adderss: ""
}
JSFiddle

Use the collection that you've already found with querySelectorAll to get the values of the value and name attributes :
var person = {}
var cars = document.querySelectorAll(".so")
for (i = 0; i < cars.length; i++) {
person[cars[i].name] = cars[i].value
}
console.log(person)
JSFiddle

Because getElementByClassName does not exist (also it would have no use in your script). Use this:
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
alert(cars[i].name)
}

Firstly, use cars variable instead of calling querySelectorAll every time.
Secondly, use addEventListener to execute code on click.
Fiddle: http://jsfiddle.net/guyavunf/3/
Code:
// HTML
<input class="so" name="Name" value="bob"></input>
<input class="so" name="LastName" value="Feyzi"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input class="submit" type="submit"></input>
// JS
document.querySelector('.submit').addEventListener('click', function() {
var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) {
var name = cars[i].name;
var value = cars[i].value;
alert(name + ': ' + value);
}
});

Related

Hyperlinks Don't Work After Creating DIVs On The Fly

I have an app that can save user input locations in localStorage. When a user goes to the saved locations page in the app, the JavaScript creates divs for each saved location and displays the key text. I want to be able to click each location and run a function. I'm stuck on getting the divs to have hyperlinks. I think the problem is in my loop. "JavaScript:Void(0)" is just a placeholder for the moment.
Here is what I have so far:
myApp.onPageInit('saved_locations', function (page) {
var fragment = document.createDocumentFragment();
var parent = document.getElementById("saved");
// iterate localStorage
for (var i = 0; i < localStorage.length; i++) {
// set iteration key name
var key = localStorage.key(i);
// use key name to retrieve the corresponding value
var value = localStorage.getItem(key);
// console.log the iteration key and value
console.log('Key: ' + key + ', Value: ' + value);
//var idNum = i.toString();
let node = document.createElement("div");
let a = document.createElement("a");
a.textContent = key;
a.href = "JavaScript:Void(0)";
node.appendChild(a);
fragment.appendChild(node);
};
parent.appendChild(fragment);
var myForm = document.getElementById("enter_location");
myForm.addEventListener('submit', function saveSearchLocation() {
var lat = document.getElementById('Latitude').value;
var lon = document.getElementById('Longitude').value;
var locationStr = document.getElementById('Location').value;
//Save location parameters to local storage
savedLocationParams = [lat, lon, locationStr];
window.localStorage.setItem(locationStr, JSON.stringify(savedLocationParams));
document.getElementById("saved").onsubmit = function(){
window.location.reload(true);
}
});
});
Here is the HTML page:
<body>
<div class="pages">
<div data-page="saved_locations" id="saved" class="page navbar-through no-
toolbar" align="center">
<h2><br><u>Enter A Location<br><br></u>
<form id="enter_location">
Latitude: <input type="text" id="Latitude" value=""><br>
Longitude: <input type="text" id="Longitude" value=""><br>
Location: <input type="text" id="Location" value=""><br>
<input type="submit" value="Submit">
</form>
<h2><u>Saved Locations</u></h2>
</div>
</div>
You have to create the a elements, and then assign the text you want to them, and then you have to put the a elements in the div.
let a = document.createElement("a");
a.textContent = "this is the link text";
a.href = "JavaScript:Void(0)";
node.appendChild(a);
If you want the value text to be linked, you can do this instead of creating the text node:
a.textContent = key;
I modified your code slightly to show an example. Just click on the "Click Here" to see the effects of the function :
//myApp.onPageInit('saved_locations', function (page) {
var clickMeToDoLoad = function() {
var fragment = document.createDocumentFragment();
var parent = document.getElementById("saved");
var fakeLocalStorage = {
"key0": "value0",
"key1": "value1",
"key2": "value2"
};
// iterate localStorage
//for (var i = 0; i < localStorage.length; i++) {
for (var i = 0; i < 3; i++) {
// set iteration key name
//var key = localStorage.key(i);
// use key name to retrieve the corresponding value
//var value = localStorage[key);
// set iteration key name
let key = Object.keys(fakeLocalStorage)[i];
// use key name to retrieve the corresponding value
let value = fakeLocalStorage[key];
// console.log the iteration key and value
console.log('Key: ' + key + ', Value: ' + value);
let idNum = i.toString();
let node = document.createElement("div");
let a = document.createElement("a");
a.textContent = key;
a.href = "JavaScript:Void(0)";
node.appendChild(a);
fragment.appendChild(node);
}
parent.appendChild(fragment);
}
<div class="pages">
<div data-page="saved_locations" id="saved" class="page navbar-through no-
toolbar" align="center">
<h2><br/><u>Enter A Location<br /><br /></u></h2>
<form>
Latitude: <input type="text" name="Latitude" value=""><br> Longitude: <input type="text" name="Longitude" value=""><br> Location: <input type="text" name="Location" value=""><br>
<input type="submit" value="Submit" onclick="return false;">
</form>
<h2><br /><u>Saved Locations</u></h2>
<button onclick="clickMeToDoLoad();">Click to demo function</button>
</div>
</div>

change attrib name with array

I have a form with this input:
<input id="cant_user" type="text" name="cant_user" value="1" onblur="addInputs()">
#userData is cloned when add a input value greater than 1 and I want to change input name from user_age to age[n]
<div id="userData">
<div class="panel-body" id="generated[0]">
<div class="form-group">
<label class="col-md-4 control-label">Age User [n]</label>
<div class="col-md-6">
<input type="number" class="form-control" name="user_age[]" value="0" required>
</div>
</div>
</div>
Javascript:
function addInputs() {
var cantUsers = document.getElementById("cant_user").value;
var countGenerated = $('[id^=generated]').length;
if (countGenerated > 0) {
$('[id^=generated]').not(':first').remove();
}
if (cantUsers != 1) {
if (cantUsers > 1 && cantUsers < 10) {
for (var i = 1; i < cantUsers; i++) {
jQuery("#userData").append(jQuery("#userData").children().first().clone());
jQuery("#userData").children().last().attr("id", "generated[" + i + "]");
for (var n = 0; n <= i; m++) {
var u = document.getElementsByName("user_age[]");
$(u).removeAttr("name").attr({
id: "generatedAge[" + n + "]",
name: "age[" + n + "]"
});
}
};
}
};
}
How can I make every label and input name shows a value from array like:
<label>Age User 1<label>
<input name="age[0]">
<label>Age User 2<label>
<input name="age[1]">
I changed some code, it maybe can help if i understand your idea correct
for ( var i = 1; i < cantUsers; i++) {
var userData = jQuery("#userData");
var childOfUserData = userData.children();
userData.append( childOfUserData.first().clone() );
childOfUserData = userData.children(); //because we just appen new data
childOfUserData.last().attr("id","generated[" + i + "]");
for ( var n = 0; n <= i; n++ ) {
var child = childOfUserData.get(i);
var userAge = $("input", $(child));//because you only have one input
userAge.attr("name","age[" + n + "]").attr("id","generatedAge[" + n + "]");
}
<input name="age[0]">
In the above code name attribute value acts as text not an array value.
To get an array value in the attribute, you need to change the JavaScript code
$("#userData").children().last().attr("id", generated[i]);
$(u).removeAttr("name").attr({
id: generatedAge[n],
name: age[n]
});
Now, if you check the attribute value, you will receive data into it.
Hope this will help you.

Replace all occurrences of "<", ">" inside value attribute

I have the requirement to replace all occurrences of "<" and ">" characters that are found inside the value attribute. I want to replace "<" and ">" characters with ""
This is my sample html:
<form name="form1">
<input type="text" value="<first set><second set><third set>" />
<input type="text" value="<fourth set><fifth set><sixth set>" />
</form>
I tried using javascript replace method but no luck.
You could use this pure JavaScript function:
function removeLessGreaterThan(html) {
// Use the DOM API to change the value attribute values:
var span = document.createElement('span');
span.innerHTML = html;
var inputs = span.querySelectorAll('input[type=text]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].setAttribute('value', inputs[i].value.replace(/[<>]/g, ''));
}
return span.innerHTML;
}
// Sample data:
var html = '<form name="form1"> <input type="text" value="Here is a >test<." /> <input type="text" value="And another >test<." /> </form>';
html = removeLessGreaterThan(html);
console.log(html);
const FORM_NAME = "form1";
var fields = document.getElementsByName(FORM_NAME)[0].getElementsByTagName("input");
for(var i = 0; i < fields.length; i++) {
fields[i].value = fields[i].value.replace(/[<>]/g, "");
}
I think you are expecting this way. Please go through the code.
function ReplaceMyValues()
{
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
if(inputs[i].type=="text")
{
var currentValue=inputs[i].value.replace(/[<>]/g, "");
inputs[i].value = currentValue;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form name="form1"> <input type="text" value="<first set><second set><third set>" /> <input type="text" value="<fourth set><fifth set><sixth set>" />
<input id="Test" type="button" value="Replace" onclick="ReplaceMyValues();"></input>
</form>
You can use jquery
$(".yourInput").val($(".yourInput").val().replace('<', '').replace('>', ''))

Giving elements new id

I want to add ids to inputs dynamicly using javascript.How can I do that.I wrote a function but it wouldn't work.
html
<form>
element 0_0 <input type = "text" class = "elements"></input>
element 0_1 <input type = "text" class = "elements"></input>
element 1_0 <input type = "text" class = "elements"></input>
element 1_1 <input type = "text" class = "elements"></input>
<input type = "button" onclick = "giveId('elements')"></input>
</form>
javascript
function giveId(className){
var array = document.getElementsByClassName(className)
for(var i = 0;i < array.length; i++){
array[i].id = "A" + i;
}
}
inputs are self closing:
<form>
element 0_0 <input type="text" class="elements" />
element 0_1 <input type="text" class="elements" />
element 1_0 <input type="text" class="elements" />
element 1_1 <input type="text" class="elements" />
<input type="button" onclick="giveId('elements')" />
</form>
and className is an element propery in javascript, so you should use a different name:
function giveId(cName) {
var arr = document.getElementsByClassName(cName)
for (var i = 0; i < arr.length; i++) {
arr[i].id = "A" + i;
}
}
FIDDLE
I tested your code and it works fine.
Have you tried selecting your new IDs?
<form>
element 0_0 <input type = "text" class = "elements"></input>
element 0_1 <input type = "text" class = "elements"></input>
element 1_0 <input type = "text" class = "elements"></input>
element 1_1 <input type = "text" class = "elements"></input>
<input type = "button" onclick = "giveId('elements')"></input>
</form>
<script>
function giveId(classname){
var array = document.getElementsByClassName(classname)
for(var i = 0;i < array.length; i++){
array[i].id = "A" + i;
}
}
</script>

Shortening JavaScript Function

I must admit, I don't know much about JavaScript that is why my question might sound little bit silly.
But what I'm trying to do is grab values from selected by name radio groups.
It looks like this
function calc() {
var op1 = document.getElementsByName('form[radio1]');
var op2 = document.getElementsByName('form[radio2]');
var op3 = document.getElementsByName('form[radio3]');
var result = document.getElementById('result');
result.value = 0;
result.value = parseInt(result.value);
for (i = 0; i < op1.length; i++) {
if (op1[i].checked) result.value = parseInt(result.value) + parseInt(op1[i].value);
}
for (i = 0; i < op2.length; i++) {
if (op2.options[i].selected) result.value = parseInt(result.value) + parseInt(op2[i].value);
}
for (i = 0; i < op3.length; i++) {
if (op3.options[i].selected) result.value = parseInt(result.value) + parseInt(op3[i].value);
}
return false;
}
And this is my form. Im using rs form for joomla.
<form action="index.php" enctype="multipart/form-data" id="userForm" method="post">
<input name="form[radio1]" value="25" id="radio20" type="radio">
<label for="radio20">Description1</label>
<input name="form[radio1]" value="35" id="radio21" type="radio">
<label for="radio21">Description2</label>
<input name="form[radio2]" value="20" id="radio20" type="radio">
<label for="radio20">Description1</label>
<input name="form[radio2]" value="30" id="radio21" type="radio">
<label for="radio21">Description2</label>
<input type="hidden" value="0" id="result" name="form[result]">
<input type="submit" class="rsform-submit-button" onclick="calc()" id="submit" name="form[submit]" value="submit">
And everything would be OK, as the function is working. the only trouble is that I have about 80 radiograms.
Is there a way to shorten it?
Use arrays of objects (like all the radio buttons, for instance) and iterate over them. Start like this:
var opts = [],
numOpts = 80;
for (var i=0; i<numOpts, i++)
{
opts.push(document.getElementsByName('form[radio' + i + ']'));
}
Edit: let's have a go at the full function. The only thing I'm not 100% sure about is whether you mean to use opX[i].checked or opX.options[i].selected (since your code does different things for op1 and op2/3). Shouldn't be too hard to extrapolate if I've guessed wrong, though.
function calc()
{
var opts = [],
numOpts = 80,
value = 0,
result = document.getElementById('result'),
i, j, opt;
for (i=0; i<numOpts; i++)
{
opts.push(document.getElementsByName('form[radio' + i + ']'));
}
numOpts = opts.length;
for (i=0; i<numOpts; i++)
{
opt = opts[i];
for (j=0; j<opt.length; j++)
{
// or did you mean:
// if (opt.options[j].selected) ?
if (opt[j].checked)
{
value = value + parseInt(opt[j].value, 10);
}
}
}
result.value = value;
return false;
}
jQuery is a great library that's like using JavaScript on steroids. It is well worth learning and there are plenty of examples out in the wild.
You can write complex "selectors" quite like this:
$('input[name=form[radio1]]').attr('checked').each(function() {
result.value = $(this).attr('value')
})
(I'm not sure if it will accept a name like "form[radio1]" as valid, but give it a try.

Categories

Resources