realtime update text in javascript by same id - javascript

How do I update the text in the id="b"?
<script type="text/javascript">
function updateb()
{
var a= document.getElementById("a").value;
var b = document.getElementById("b").innerHTML = a * 10;
}
</script>
<input type="text" id="a" name="a" value="10" onKeyUp="updateb();" /><p id="b" name="b"></p>
<input type="text" id="a" name="a" value="20" onKeyUp="updateb();" /><p id="b" name="b"></p>
<input type="text" id="a" name="a" value="30" onKeyUp="updateb();" /><p id="b" name="b"></p>

1.) IDs should be always unique in a page.
2.) GetElementById always returns only one element with same id if there are multiple ids with same value
3.) for above question you can try getElementsByName. it is quite similar to getElementById with a diff that it will give u all elements with same name. if you do
x= document.getElementsByName("b");
x[0] will contain first one
x[1] will contain 2nd one
x[2] will contain 3rd one
If you want it be done by getElementById then change ur elements id with any other unique name like:
<script type="text/javascript">
function updateb(Src)
{
var a= Src.value;
document.getElementById("b" + Src.id.substr(1)).innerHTML = a * 10;
}
</script>
<input type="text" id="a1" name="a" value="10" onKeyUp="updateb(this);" /><p id="b1" name="b"></p>
<input type="text" id="a2" name="a" value="20" onKeyUp="updateb(this);" /><p id="b2" name="b"></p>
<input type="text" id="a3" name="a" value="30" onKeyUp="updateb(this);" /><p id="b3" name="b"></p>

Note that an id field must be unique to a document. That is, you can't have three elements with the same ID as in your example.
Otherwise, the code you posted should update the contents of B, though obviously you'd need to do this in response to an onchange or onblur event on the input field.

As others have pointed out, all elements in a document should have a unique id.
In your case, however, an id may not be required at all, as you can use the relative positions of elements to achieve your aims.
This example doesn't need an id or a name, but this may differ in your case, depending on your overall requirements.
<script type="text/javascript">
function updateb(inputElement)
{
var a = inputElement.value;
var target = inputElement.nextSibling;
if(target != null){
target.innerHTML = a * 10;
}
}
</script>
<input type="text" value="10" onKeyUp="updateb(this);" /><p></p>
<input type="text" value="20" onKeyUp="updateb(this);" /><p></p>
<input type="text" value="30" onKeyUp="updateb(this);" /><p></p>
Using a solution like the one offered by #KoolKabin may be better in the long run, as it is more tolerant to changes in the HTML structure. Either way, there are usually several different ways to approach any given problem, and you should evaluate the best for the circumstances.

Related

it needs to count the values but its doesnt work javascript

i have made a small code but he needs to count the value + a other value but its not work but he only places everything side by side. its a realy stupid question i know. I just do not see how it should be done.
You are trying to add two strings.
When you get value, notice your value is in quotes making it a string. You can parse int from string. You want to add something to handle when only 1 number is selected.
<!DOCTYPE html>
<html>
<body>
<form id="first" name="first">
<input type="radio" name="rads" value="1" />1
<input type="radio" name="rads" value="2" />2
<input type="radio" name="rads" value="3" />3
<input type="radio" name="rads" value="4" />4
</form>
<form id="second" name="second">
<input type="radio" name="rads" value="1" />1
<input type="radio" name="rads" value="2" />2
<input type="radio" name="rads" value="3" />3
<input type="radio" name="rads" value="4" />4
</form>
<span id="result"></span>
<script>
document.onclick = function hoi(){
var first = document.first.rads.value;
var second = document.second.rads.value;
var all = parseInt(first) + parseInt(second);
result.innerHTML = all;
}
</script>
</body>
</html>
The value property on a input is string, so there is string concatenation going on, convert both inputs to a number then add:
result.innerHTML = Number(first) + Number(second)
First of all, welcome to StackOverflow!
The solution to your problem is very simple: The value property returns a string, and using + on strings concatenates them. You first have to convert it to a number using parseInt(), and then add them together which would look like so:
var all = parseInt(first) + parseInt(second);

How to get html input in JavaScript?

I am using the code below in a html form:
<input type="text" name="cars[]" required>'
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
I would like to get the answers from all the inputs in JavaScript.
How can this be done?
I have the following WRONG code for this:
var element = document.getInput("cars[]");
for (i = 0; i < element.length; i++) {
alert(element[i].value);
}
You have to use document.getElementsByName() like this:
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
alert(element[i].value);
}
<input type="text" name="cars[]" value="a" required>
<input type="text" name="cars[]" value="b" required>
<input type="text" name="cars[]" value="c" required>
These two things in pure JavaScript net approximately the same result. The first is using the HTML form element to find all of the input elements attached to it. However, the syntax for finding the array called "cars[]" is troublesome and in my opinion a tad annoying. If I was going to do something in pure JavaScript I'd probably prefer the second way, using document.querySelectorAll.
window.addEventListener('load', function() {
var form = document.getElementById('thing');
form.elements['cars[]'].forEach(function(el, i) {
console.log("value is ", el.value)
}); //Form.elements[] array has been available since Chrome 7 or so. It should be available for use in just about any browser available.
var items = document.querySelectorAll('[name="cars[]"]');
items.forEach(function(el, i) {
console.log("Item Value is ", el.value)
});
});
<form id="thing">
<input type="text" name="cars[]" value="1" />
<br />
<input type="text" name="cars[]" value="2" />
<br />
<input type="text" name="cars[]" value="3" />
<br />
<input type="text" name="cars[]" value="4" />
<br />
<input type="submit" value="submit" />
</form>
You write
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
In HTML, you can have many inputs in the same form with the same name, regardless of that name having a [] suffix or not. This has always been used for, say, checkboxes. Most server-side libraries will then return the values for those inputs as an array.
An example of gathering all values for inputs with a given name could be the following:
document.querySelector("#b").addEventListener("click", () => {
const values = [];
document.querySelectorAll("input[name='color']").forEach(e => values.push(e.value));
console.log(values); // outputs ["foo", "bar", "baz"] if values unchanged
});
input { display: block; margin: 5px; }
<label>Enter your favorite colors
<input type="text" name="color" value="foo"/>
<input type="text" name="color" value="bar"/>
<input type="text" name="color" value="baz"/>
</label>
<label>
Enter your favorite food
<input type="text" name="food" value="flub"/>
</label>
<button id="b">Click me to output favorite colors</button>
You can give same id to all inputs like
<input type="text" id="inputId" name="cars[]" required>'
In Javascript iterate the element to get the value
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
console.log(element[i].value);
}

jQuery selector with asteriks

I have some multiple radio buttons on a page with a different id. Depending on the choosen value a upload button or a textbox must show up. But because it's 10 times almost the same code (the only difference is a number) I was looking for a solution where I can reuse the code.
Example of two radio groeps:
<input type="radio" name="typePhoto2" id="foto2" value="photo">
<input type="radio" name="typePhoto2" id="video2" value="video">
<input type="radio" name="typePhoto3" id="foto3" value="photo">
<input type="radio" name="typePhoto3" id="video3" value="video">
I known there is a way to use jQuery with a * to select multiple elements, but what I want is to use the value of '*' to provide which number is choosen.
$("[id^=typePhoto]").click(function(){
var value = [number after the id];
})
Is there a way to do this? Otherwise I have to copy paste 10 times the same code with only a number as difference.
You can always reach the id of the current target through the event object,
and then with a little regex you're done:
$("[id^='foto']").click(function(e){
var id = e.currentTarget.id
var value = id.match(/[0-9]$/)[0];
console.log(value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="typePhoto2" id="foto2" value="photo">
<input type="radio" name="typePhoto3" id="foto3" value="photo">
You need to fix the selector to target all element with name attribute value starts with typePhoto .then get the current id using clicked element context this and remove static part using .replace():
$("[name^=typePhoto]").click(function(){
var value = this.id.replace("foto","").replace("video","");
});
Working Snippet :
$("[name^=typePhoto]").click(function(){
var value = this.id.replace("foto","").replace("video","");
console.log(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="typePhoto2" id="foto2" value="photo">
<input type="radio" name="typePhoto2" id="video2" value="video">
<input type="radio" name="typePhoto3" id="foto3" value="photo">
<input type="radio" name="typePhoto3" id="video3" value="video">
You could try:
$('[id*="typePhoto"]')
or
$('input[type="radio"]');
Cheers
A better way to do that would be to give them all the same class. For instance class="photo-button". then you could use:
$(".photo-button").click(function(){...})
Try like this
$( "input[name*='typePhoto']" ).click( function(){
// your code
});

Advanced use of jQuery serializeArray()

I'm currently submitting a form via ajax and pass in a manually created data variable that looks a bit like this:
var data = 'answer1='
+ $("input[name=question_1]:checked").val()
+ '&q1_option=' + $("input[name=question_1]:checked").attr("id")
This continues throughout the list of form elements obviously increasing incrementally question_2, question_3 etc. The problem is that this is a bit messy. I'd like to use jQuery serializeArray but, to do this I would need to pass in an extra parameter. I need to pass the input value and the input id as this id is used in the data.
Is there a way I can achieve this using jQuery serializeArray()?
Example form markup:
<label>What is your gender?<span class="required"> *</span></label>
<input id="1" type="radio" name="question_1" value="Male"><label class="standard" for="1">Male</label><br>
<input id="2" type="radio" name="question_1" value="Female"><label class="standard" for="2">Female</label><br>
<label>How old are you?<span class="required"> *</span></label>
<input id="3" type="radio" name="question_2" value="Under 25"><label class="standard" for="3">Under 25</label<br>
<input id="4" type="radio" name="question_2" value="25-29"><label class="standard" for="4">25-29</label><br>
<input id="5" type="radio" name="question_2" value="30-39"><label class="standard" for="5">30-39</label><br>
<input id="6" type="radio" name="question_2" value="40-49"><label class="standard" for="6">40-49</label><br>
<input id="7" type="radio" name="question_2" value="50-59"><label class="standard" for="7">50-59</label><br>
<input id="8" type="radio" name="question_2" value="60+"><label class="standard" for="8">60+</label><br>
First of all, let me point out that this looks like a misuse of forms. If the name of the form element would be "answer1" instead of "question_1", and if your options would be named "q1_option" rather than "question_1", and if you accessed their values rather than their ids, you would be able to serialize the form in a simple one-liner, and, essentially, this is the meaning that name and value are intended to convey.
Having said that, $.serializeArray yields an array of key/value pairs. It's hard to see what you would want $.serializeArray to do in your specific scenario. If you want such an array, you could construct it yourself:
var keyValuePairs = [];
keyValuePairs.push({ name: 'answer1', value: $('input[name=question_1]:checked').val() })
var options = $('input[name^="question_"]:checked');
for(var i = 0; l = options.length; i < l; i++) {
keyValuePairs.push({
name: 'q' + i + '_option',
value: options.get(i).attr('id')
});
}
Given such an array, you could serialize it to a string like the one in your example, using
var data = $.param(keyValuePairs);

Slow JavaScript

I've got an HTML form where the maximum field value is set to 1 character. As a result, the JavaScript needs to be super-fast. But upon testing, it appears I am too fast for the script, so it misses characters unless I type slowly.
<script type="text/javascript">
function formfocus() {
document.getElementById('element').focus();
}
window.onload = formfocus;
function moveOnMax(field,nextFieldID){
if(field.value.length >= field.maxLength){
document.getElementById(nextFieldID).focus();
}
}
</script>
<input class="text" type="text" name="1" id="element" maxlength="1" onkeyup="moveOnMax(this,'2')"><input class="text" id="2" onkeyup="moveOnMax(this,'3')" type="text" name="2" maxlength="1">
Anyone know a way to speed this up, or am I stuck with having to instruct visitors to type slowly?
As you have mentioned maxlength of all fields are 1 character, then why to check length of the values of each field just in onkeyup event handler of every field make the focus to next field.
<script type="text/javascript">
function formfocus() {
document.getElementById('element').focus();
}
window.onload = formfocus;
function moveOnMax(nextFieldID){
document.getElementById(nextFieldID).focus();
}
</script>
<input class="text" type="text" name="1" id="element" maxlength="1" onkeyup="moveOnMax('2')">
<input class="text" id="2" onkeyup="moveOnMax('3')" type="text" name="2" maxlength="1">
<input class="text" id="3" onkeyup="moveOnMax('4')" type="text" name="2" maxlength="1">

Categories

Resources