I'm adding new inputs dynamically. And I would also like to read values dynamically from them. My championName variable doesn't work in JS.
<form name="second_form" id="second_form" action="#" method="POST" style="margin: 0;" >
<div id="p_scents">
<p>
<label for="p_scnts">
<input type="text" id="p_scnt" size="20" list="champions" name="champion[]" value="" placeholder="Enter Champion's name">
<datalist id="champions"></datalist>
Add General Change<a></a>
Add Spell<a></a>
</label>
</p>
</div>
<br/><input type="submit" value="submit">
</form>
function val(doublechamp) {
var championsWithExtraSpells = ["Aatrox", "Elise", "Fizz", "Heimerdinger", "Jayce", "Lee Sin", "Nidalee", "Rek'Sai","Twisted Fate"];
var champion = this["champion[]"];
var championName = document.getElementsByName("Champion[]").value;
if($.inArray(championName, championsWithExtraSpells)==-1){
var existsInArray = false;}
else{
var existsInArray = true;}
d = document.getElementById("change[]").value;
var spellname = document.getElementById("ttt");
spellname.value=champions[""+championName+""][change(d, existsInArray)];
}
Collection returned by getElementsByName() in the line, so just replace it.
UPDATED
JS :
Replace :
var championName = document.getElementsByName("Champion[]").value;
By :
for(var i=0;i<document.getElementsByName("champion[]").length;i++)
var championName = document.getElementsByName("champion[]")[0].value;
Now you can get all the inputs values.
There are couple of changes you need to make:
- You're not invoking the function anywhere in the code you're showing
you'll need to add an onChange clause to the input or an onsubmit to the form to check the values..
the name of an element can't contain [] - so you should remove those from the name;
<input type="text" id="p_scnt" size="20" list="champions" name="champion" value="" placeholder="Enter Champion's name">
getElementsByName returns nodelist, not a single node (even if there's only one match). If you make the following changes you'll get farther:
And in the script change these two lines:
var championName = document.getElementsByName("champion");
if($.inArray(championName[0].value, championsWithExtraSpells)==-1){
Related
I am trying to create ID dynamically in the HTML object and use of getElementById() in my javascript to access the HTML input value based on the button I clicked and insert into their respective HTML Select list.
My HTML snippets:
<input type="text" id="addDesc1"><input type="button" value="Add" onclick="addDescText(1)">
<input type="text" id="addDesc2"><input type="button" value="Add" onclick="addDescText(2)">
....
....
<select id="desc1">....</select>
<select id="desc2">....</select>
My javascript snippets:
function addDescText(id) {
var descText = document.getElementById("addDesc".concat(id)).value;
var selList = document.getElementById("desc".concat(id));
....
....
some javascript to add the respective description to their respective select list
....
}
concat() is an array method, you can not use that on string. Simply use + to concatenate the parameter with the string.
Demo:
function addDescText(id) {
var descText = document.getElementById("addDesc"+id).value;
var selList = document.getElementById("desc"+id);
console.log(descText);
console.log(selList);
}
<input type="text" id="addDesc1"><input type="button" value="Add" onclick="addDescText(1)">
<input type="text" id="addDesc2"><input type="button" value="Add" onclick="addDescText(2)">
<select id="desc1">....</select>
<select id="desc2">....</select>
I would encourage you to make use of the event parameter that is passed to all event handlers (on-click-event in your case) and add that handler programmatically.
A possible solution would be
HTML
<input type="text" id="text1">
<input type="button" value="Add" class="add-desc-button" data-target="1">
JS
// get all buttons
let allButtons = document.querySelectorAll('.add-desc-button')
// add event handler
for (let i=0; i<allButtons.length; i++) {
allButtons[i].addEventHandler('click', addDescriptionHandler)
}
// event handler
function addDescriptionHandler(event) {
// retrieve the number you passed in before like this
let number = event.target.getAttribute('data-target')
// ... your code here
}
I would like to copy the value from an input in one form to the value of an input(with the same name) of the next form down. The forms and inputs are named the same. All it needs to do is copy the value of the title input to the title input one form down.
<form>
<input name="file" value="1.xml">
<input name="title" id="title" value="Smith">
<input type="submit" id="copy-down" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title" value="Anderson">
<input type="submit" id="copy-down" value="copy">
</form>
etc...
In this case when the top "copy" button is clicked I would like jquery to overwrite Anderson with Smith.
$('#title').attr('value'));
Gives me Smith but I'm not sure what to do with that value once I have it.
Change HTML to this:
<form>
<input name="file" value="1.xml">
<input name="title" id="title1" value="Smith">
<input type="submit" id="copy-down1" value="copy">
</form>
<form>
<input name="file" value="2.xml">
<input name="title" id="title2" value="Anderson">
<input type="submit" id="copy-down2" value="copy">
</form>
Javascript:
function copyHandler() {
var copyVal = document.getElementById("title1").value;
var replaceInput = document.getElementById("title2");
replaceInput.value = copyVal;
}
document.getElementById("copy-down1").onclick = function(){
copyHandler();
return false;
}
Some notes:
This is so straightforward in vanilla javascript that I didn't add the jQuery code.
You should never assign multiple elements to the same ID, class or name can be used for that purpose.
The return false; portion of the onclick function is necessary so that the form doesn't reload when you click your submit button.
Let me know if you have any questions.
you can try
$(document).ready(function(){
$('form').on('submit', function(e){
e.preventDefault();
var GetNameAttr = $(this).find('input:nth-child(2)').attr('name');
var GetTitleValue = $(this).find('input:nth-child(2)').val();
var NextFormNameAttr = $(this).next('form').find('input:nth-child(2)').attr('name');
if(NextFormNameAttr == GetNameAttr){
$(this).next('form').find('input:nth-child(2)').val(GetTitleValue );
}
});
});
Note: this code will change the second input value in next form with
the second input value of form you click if the name is same .. you
can do the same thing with the first input by using :nth-child(1)
Demo here
if your forms dynamically generated use
$('body').on('submit','form', function(e){
instead of
$('form').on('submit', function(e){
for simple use I create a function for that
function changeNextValue(el , i){
var GetNameAttr1 = el.find('input:nth-child('+ i +')').attr('name');
var GetTitleValue1 = el.find('input:nth-child('+ i +')').val();
var NextFormNameAttr1 = el.next('form').find('input:nth-child('+ i +')').attr('name');
if(NextFormNameAttr1 == GetNameAttr1){
el.next('form').find('input:nth-child('+ i +')').val(GetTitleValue1);
}
}
use it like this
changeNextValue($(this) , nth-child of input 1 or 2);
// for first input
changeNextValue($(this) , 1);
// for second input
changeNextValue($(this) , 2);
Working Demo
I'm trying to create an HTML form which takes the text from multiple textboxes (in this case, 3) and adds the content of each to a list in a separate div, as well as create a new object "employee", all via the click of a button. My goal is to imitate adding employees to a database, using an employee id, first name, and last name as variables. I am looking to accomplish this using pure javascript.
What I have so far is:
<form>
ID Number:
<br>
<input type="text" id="idNumber">
<br>First name:
<br>
<input type="text" id="firstName">
<br>Last name:
<br>
<input type="text" id="lastName">
</form>
<br>
<button type="submit" onclick="myFunction(list)">Submit</button>
<div id="container">
<ul id="list"></ul>
</div>
In a separate JavaScript file:
function myFunction(list){
var text = document.getElementById("idNumber","fName","lName").value;
var li = "<li>" + text + "</li>";
document.getElementById("list").replaceChild(li);
}
When I debug my code it seems to be setting the values fine, but I receive no actual output of my list.
None of the input elements you selected had a class name. You can also do this with document.getElementById. Just add ids to all your form elements.
Your code should look something like this.
function myFunction(list){
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
var li = document.createElement("li");
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
}
http://jsfiddle.net/nb5h4o7o/3/
Your list wasn't being appended to because you weren't actually creating the elements. replaceChild should have been appendChild and you should have created a list element with document.createElement.
Your code is full of problems, look at the document.getElementById and Node.replaceChild docs.
I've created a version for you that we get all the input elements of your form (using querySelectorAll), and then we use Array.prototype.map to turn them into "<li>[value]</li>", and then Array.prototype.join to turn that array into a single string.
Then, we get that string and set the #list.innerHTML property.
document.querySelector('button').addEventListener('click', function(e) {
var form = document.querySelector('form'),
list = document.getElementById('list');
list.innerHTML = [].map.call(form.querySelectorAll('input'), function(el) {
return '<li>' + el.value + '</li>';
}).join('');
});
<form>
ID Number:
<br>
<input type="text" id="idNumber">
<br>First name:
<br>
<input type="text" id="firstName">
<br>Last name:
<br>
<input type="text" id="lastName">
</form>
<br>
<button type="submit">Submit</button>
<div id="container">
<ul id="list"></ul>
</div>
I have mayn different question first and for all there is this pretty normal for who wants to know your firstname and lastname (its German but I hope this deosent matter)
<form name="formular" action="" onsubmit="">
<p>
<label for="vorname">Vorname:</label>
<input value="" type="text" name="vorname" id="vorname" size="25">
</p>
<p>
<label for="nachname">Nachname:</label>
<input type="text" name="nachname" id="nachname" size="25">
</p>
<p><input type="button" value="Absenden" onclick="doFunction();" /></p>
</form>
Then i want to use a function who gets the Name from the form and then shows all Names who ever fill out that form like a Guestbook. Until now i just made it to call an alert whon says "Hallo" but i dont even know how to use The form input as Variables.
I hope u can help me, pls only use JS and HTML.
You can capture the fields and add them to an array, and then print that array onto the page.
Here's a Fiddle containing my code. The existing add button appends to a ul element above the form and saves the name to a global array. I added clear and load buttons as well, so that you can see how to populate the list from the array.
<ul id="guestList">
</ul>
<form name="formular" action="" onsubmit="">
<p>
<label for="vorname">Vorname:</label>
<input value="" type="text" name="vorname" id="vorname" size="25"/>
</p>
<p>
<label for="nachname">Nachname:</label>
<input type="text" name="nachname" id="nachname" size="25"/>
</p>
<p>
<input type="button" value="Absenden" onclick="storeVals();" />
<input type="button" value="Clear List" onclick="clearList();" />
<input type="button" value="Load List" onclick="loadList();" />
</p>
</form>
And javascript:
var names = []; //global scope
function storeVals() //declare function to store the input
{
//document.getElementById finds the element with the
//corresponding ID. In this case I'm getting the objects
//behind each of the input boxes, and retrieving their value properties
//(the text entered in them). I'm also concatenating them together with
//the plus sign (+) operator, and adding a space between them with the ' '
//I'm storing the result of all that in a variable called name.
var name = document.getElementById('vorname').value + ' ' + document.getElementById('nachname').value;
//I'm accessing the names array I declared above. The elements in the
//array are accessed using an index which counts from 0.
//So to get the first element, I would do names[0].
//In this case I'm using names.length instead of a number, as it will return
//the number of elements currently in the array. When there are zero, it will return 0.
//When there is one, it will return 1, which happens to be the index for the second element.
//The means I'm always assigning the name to the element after the last existing one.
names[names.length] = name;
alert(names); //just to help see what's going on. Remove this when you don't need it anymore.
//Uses document.getElementById again, this time to get the object behind my ul list.
//And calls my appendToList function below, passing it my name variable and a
//reference to the list object.
appendToList(name, document.getElementById('guestList'));
}
function appendToList(name,ulist){
//this constructs a <li> object and stores it in a variable.
var li = document.createElement("li");
//this adds the text of the name inside the <li>
//so if name is equal to "john smith", I've built:
//<li>john smith</li>
li.appendChild(document.createTextNode(name));
//adds the li as a child of my existing list object.
//so:
// <ul id="guestList"><li>john smith</li></ul>
ulist.appendChild(li);
}
function clearList(){
//gets my ul list object with the id "guestList"
//sets its innerHTML (all of its contents) to an empty string
//so regardless of what's inside, it becomes <ul id="guestList"></ul>
document.getElementById('guestList').innerHTML = '';
}
function loadList(){
//got my ul list object by id again.
var list = document.getElementById('guestList');
//for loop - essentially this means start the variable i at 0
//keep looping while i < names.length, and increment i by 1
//each time we iterate through the loop.
for(i=0;i < names.length; i++){
//call the appendToList function above, and pass it names[i] and my list object
//so essentially, loop over every name in the array and call that function with
//it to add the name to the list.
appendToList(names[i],list);
}
}
Here are some specific reference materials for some of things I've done.
Arrays
ul DOM object
the document object
document.getElementById
But you need to be aware, if you're just using client-side javascript, this data is not going to survive a page refresh, and it will not be available if the page is accessed from another browser.
What you want to do is implement the JavaScript function to get the name. Here's an example:
function doFunction()
{
var name = document.getElementById('vorname').value;
alert("hallo " + name);
}
<form name="formular" action="" onsubmit="">
<p>
<label for="vorname">Vorname:</label>
<input value="" type="text" name="vorname" id="vorname" size="25">
</p>
<p>
<label for="nachname">Nachname:</label>
<input type="text" name="nachname" id="nachname" size="25">
</p>
<p><input type="button" value="Absenden" onclick="doFunction();" /></p>
</form>
Now you can do something with the name. Maybe you can store it as a global variable like so:
var name = "Guest";
function doFunction()
{
name = document.getElementById('vorname').value;
//do something here
}
And then you change the content of the website on the same page. But you must not navigate from that page; otherwise you may want to use local storage or a server-sided scripting language.
I cannot find the accept answer on here.
Currently I have a simple html form, that allows the user to enter text, in this case a user name.
<form class="Find Friend">
<div class="error" style="display:none"></div>
<input type="text" id="friendsearch" placeholder="Find Friend" class="input-field" required/>
<button type="submit" class="btn btn-login">Find</button>
</form>
I want to capture that name in a variable for later use. Do I simply use ?
var findFriend = friendsearch;
To keep the var updating on each user input, you can use.
http://jsfiddle.net/gRZ7g/
var friendName;
$('#friendsearch').on('keyup', function(e) {
friendName = $(this).val();
});
$('.show-value').click(function(e) {
alert(friendName);
});
You can get it like this:
var findFriend = $('#friendsearch').val();
You have to use the jQuery selector to select the element by its id.