I have a short javascript code that updates the content of a div element (box1 in the example below). It replaces the default text ("hello") with the text typed in an input element.
I would like to modify this code so it'd update not only the box1 div, but box2 and box3 too. I tried to use getElementsByClassName, but I was unable to make it work. I would be very grateful if somebody'd help me. Thank you.
<div class="font1" id="box1">hello</div>
<div class="font2" id="box2">hello</div>
<div class="font3" id="box3">hello</div>
<input type='text' name='fname' class='chatinput' onkeyUp="document.getElementById('box1').innerHTML = this.value" />
This should work for you :)
document.querySelector('.chatinput').onkeydown = function(){
var box1 = document.querySelector('#box1'),
box2 = document.querySelector('#box2'),
box3 = document.querySelector('#box3');
box1.innerHTML = box2.innerHTML = box3.innerHTML = (this.value);
}
You basicly create a onkeydown event, and attach it to the input.chatinput. I advise you, not to use inline javascript in the HTML
Try this
<div class="font1" id="box1">hello</div>
<div class="font2" id="box2">hello</div>
<div class="font3" id="box3">hello</div>
<input type='text' name='fname' class='chatinput' onkeyUp="document.getElementById('box1').innerHTML = this.value; document.getElementById('box2').innerHTML = this.value; document.getElementById('box3').innerHTML = this.value; " />
Demo Here
document.getElementsByClassName('box') return list of element so you should do this in a for loop
function onKeyUp($this){
for(var i in document.getElementsByClassName('box'))
document.getElementsByClassName('box')[i].innerHTML = $this.value
}
<div id="box1" class="box">hello</div>
<div id="box2" class="box">hello</div>
<div id="box3" class="box">hello</div>
<input type='text' name='fname' class='chatinput' onkeyUp="onKeyUp(this)" />
jQuery:
jsfiddle
function foo(value){
$("div").each(function(){
this.innerHTML = value;
})
};
angular:
jsfiddle
<body ng-app>
<div class="font1" id="box1">Hello {{value}}</div>
<div class="font2" id="box2">hi {{value}}</div>
<div class="font3" id="box3">nihao {{value}}</div>
<input type='text' name='fname' class='chatinput' ng-model="value" />
</body>
You're on the right track. Just use the same command three times, either inline:
<input type="text" name="fname" class="chatinput" onkeyUp="
document.getElementById('box1').innerHTML = this.value;
document.getElementById('box2').innerHTML = this.value+'hello';
document.getElementById('box3').innerHTML = this.value+'world';" />
or use a JavaScript function:
<script>
function clickMe(s){
document.getElementById("box1").innerHTML = s;
document.getElementById("box2").innerHTML = s+"hello";
document.getElementById("box3").innerHTML = s+"world";
}
</script>
<input type="text" name="fname" class="chatinput" onkeyUp="clickMe(this.value)" />
(Side note: Use double quotes for HTML-attributes. Even though all browser will understand you if you use single quotes, the double quote is the standard and the only allowed way if you want to be XML/XHTML/HTML5-compatible)
Related
Here is my HTML:
<div class="box">
<input type="file" name="file-7" id="file-7" class="inputfile inputfile-6" accept="image/png,image/gif,image/jpeg" />
<label for="file-7">
<span>This is test</span>
<strong>Upload photo</strong>
</label>
</div>
I want to clear the text (if any) of the span using jquery. I have written the code:
$('#file-7').on('change', function(){
var spn = $(this).closest('span');
spn.attr('text','');
});
The text is not getting removed. What am I doing wrong?
you just need to do that
spn.html('');
we don't need to write $() with variable
$('#file-7').on('change', function(){
var spn = $(this).closest('.box').find('span');
spn.text('');
});
Explanation: You have to find the closest parent element which has the span where you are trying to replace text. Here the parent is .box & then find the span in it.
2nd mistake you made is $(spn).attr('text','');. here there is no need of $() & no use of attr(). You can do as simple as spn.text('');
Working sample for you:
$('#file-7').on('change', function(){
var spn = $(this).closest('.box').find('span');
spn.text('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<input type="file" name="file-7" id="file-7" class="inputfile inputfile-6" accept="image/png,image/gif,image/jpeg" />
<label for="file-7">
<span>This is test</span>
<strong>Upload photo</strong>
</label>
</div>
You can replace text with text function in jQuery. And you have a typo error your variable is spn but you are using it as $(spn).
$('#file-7').on('change', function(){
var spn = $(this).next('label').find('span');
spn.text('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<input type="file" name="file-7" id="file-7" class="inputfile inputfile-6" accept="image/png,image/gif,image/jpeg" />
<label for="file-7">
<span>This is test</span>
<strong>Upload photo</strong>
</label>
</div>
I simply want to have a textbox on my webpage, using the HTML form, and input tags, and be able to have the inputted value be used by the Javascript on the page. My HTML looks like this:
<div id="firstq">
<form id="firstbox">
Choice: <input id="firstinput" type="text" name="choice">
</form>
</div>
and the Javascript I'm trying to use looks like this:
var topMenuChoice = document.getElementById("firstinput");
document.write(topMenuChoice);
}
However, all I see on the webpage, underneath the textbox, is "[object HTMLInputElement]". What do I do to get this to work right?
Thanks
here's an example with change event listener for firing a function when there's a change in form
var div = document.querySelector('div');
var topMenuChoice = document.getElementById("firstinput");
topMenuChoice.addEventListener('change',function(e){
div.innerHTML = e.target.value/***e.target.value is your input***/
var divInner = div.innerHTML;
setTimeout(function(){
document.write(divInner);
},2000)
})
<form id="firstbox">Choice:
<input id="firstinput" type="text" name="choice" value=66>
</form>
<div>look here!!</div>
Check this !
document.write(document.forms['firstbox'].firstinput.value);
OR
var topMenuChoice = document.getElementById("firstinput");
document.write(topMenuChoice.value);
}
See http://www.w3schools.com/jsref/prop_text_value.asp
var htmlInputElementObjet = document.getElementById("firstinput");
document.write(htmlInputElementObjet.value);
<div id="firstq">
<form id="firstbox">
Choice: <input id="firstinput" type="text" name="choice" value="initial value">
</form>
</div>
If you want to get the text typed in your input you need to use the value property of the element. You can also use another HTML tag to show the results (avoid using document.write):
HTML
<div id="firstq">
<form id="firstbox">
Choice: <input id="firstinput" type="text" name="choice">
</form>
<div id="result"></div>
</div>
JS
var topMenuChoice = document.getElementById("firstinput");
document.getElementById("result").innerHTML = topMenuChoice.value;
You have to consider the usage of an event (click, keypress) to control the exactly moment to retrieve the input value.
JS
document.getElementById('firstinput').addEventListener('keypress', function(e) {
if(e.which == 13) { //detect enter key pressed
e.preventDefault();
document.getElementById('result').innerHTML = this.value;
}
});
use the value property
var topMenuChoice = document.getElementById("firstinput");
document.write(topMenuChoice).value;
}
jQM code
for(var key in sessionStorage)
{
var item = sessionStorage.getItem(key);
var viewItem = $.parseJSON(item);
var titleR = viewItem.title;
$(".showTitleR").val(titleR);
}
html code
<div role="main" class="ui-content">
<div>
<input class="showTitleR" type="text" value="one and last value" />
</div>
</div>
The problem is that I can set only one and last value.
What I want is the list of all keys like this:
<div role="main" class="ui-content">
<div>
<input class="showTitleR" type="text" value="first" />
<input class="showTitleR" type="text" value="..." />
<input class="showTitleR" type="text" value="last" />
</div>
</div>
How can I solve it? Any help will be appreciated.
From what I see and if I understand correctly what are you trying to do - you are changing value for the same HTML element. You either create new HTML element or clone current and then change its value.
var item = $(".showTitleR");
item.clone().append(item.parent());
Try this:
for(var key in sessionStorage){
var item = sessionStorage.getItem(key);
var viewItem = $.parseJSON(item);
var titleR = viewItem.title;
$(".showTitleR:eq(0)").clone().val(titleR).insertAfter($(".showTitleR:last");
}
Hi I have several text input boxes, and i have a clear button, they all share the same name and i wish to clear them all using one function, and this be done without ID's as that takes up too much space
my code thus far looks like this:
var Id;
var Name;
function Check(id, name) {
Id = document.getElementById(id);
Name = document.getElementById(name);
if (Id.value == id) {
Name.checked = true;
alert('correct');
return;
} else {
Name.checked = false;
alert('incorrect');
}
}
function ClearP() {
document.getElementsByName("input").innerHTML = '';
}
my html looks like this
<div class="content">
<div class="main_story" style="margin-bottom:20px;">
<p class="sentence">the word to go here -></p>
<input id="here" name="input" class="sentence" type="text" size="7">
<p class="sentence">is here</p>
<button style="float:right" id="correct" onClick="Check('here', 'aShow');">Correct?</button>
<input style="float:right" name="aShow" id="aShow" type="checkbox" value="">
</div>
<div class="main_story" style="margin-bottom:20px;">
<p class="sentence">the word to go here -></p>
<input id="you" name="input" class="sentence" type="text" size="7">
<p class="sentence">is you</p>
<button style="float:right" id="correct" onClick="Check('you', 'bShow');">Correct?</button>
<input style="float:right" name="bShow" id="bShow" type="checkbox" value="">
</div>
<button onClick="ClearP();">Clear</button>
</div>
all help is much appreciated :) thank you :)
function ClearP(){
var inputs = document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
inputs[i].value = '';
}
Give all of them another class (something like "clearable", perhaps?), then find and clear all items with that class.
How about using jQuery, and something like this:
$('[name="input"]').val("");
Please forgive me if I repeat the question.
I have HTML that all elements inside a div tag has different id, suppose I have already get the reference to the div, is there any simple way to get the element by its id without iterate all elements with that div?
here is my sample html:
<div id="div1" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
<div id="div2" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
You may try something like this.
Sample Markup.
<div id="div1" >
<input type="text" id="edit1" />
<input type="text" id="edit2" />
</div>
<div id="div2" >
<input type="text" id="edit3" />
<input type="text" id="edit4" />
</div>
JavaScript
function GetElementInsideContainer(containerID, childID) {
var elm = {};
var elms = document.getElementById(containerID).getElementsByTagName("*");
for (var i = 0; i < elms.length; i++) {
if (elms[i].id === childID) {
elm = elms[i];
break;
}
}
return elm;
}
Demo: http://jsfiddle.net/naveen/H8j2A/
A better method as suggested by nnnnnn
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
Demo: http://jsfiddle.net/naveen/4JMgF/
Call it like
var e = GetElementInsideContainer("div1", "edit1");
var x = document.getElementById("parent").querySelector("#child");
// don't forget a #
or
var x = document.querySelector("#parent").querySelector("#child");
or
var x = document.querySelector("#parent #child");
or
var x = document.querySelector("#parent");
var y = x.querySelector("#child");
eg.
var x = document.querySelector("#div1").querySelector("#edit2");
You don't want to do this. It is invalid HTML to have more than one element with the same id. Browsers won't treat that well, and you will have undefined behavior, meaning you have no idea what the browser will give you when you select an element by that id, it could be unpredictable.
You should be using a class, or just iterating through the inputs and keeping track of an index.
Try something like this:
var div2 = document.getElementById('div2');
for(i = j = 0; i < div2.childNodes.length; i++)
if(div2.childNodes[i].nodeName == 'INPUT'){
j++;
var input = div2.childNodes[i];
alert('This is edit'+j+': '+input);
}
JSFiddle
A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.
You could change your HTML to this:
<div id="div1" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
<div id="div2" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
Then, you could get the first item in div1 with a CSS selector like this:
#div1 .edit1
On in jQuery:
$("#div1 .edit1")
Or, if you want to iterate the items in one of your divs, you can do it like this:
$("#div1 input").each(function(index) {
// do something with one of the input objects
});
If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.
If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.
You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.
A simple way to do what OP desires in core JS.
document.getElementById(parent.id).children[child.id];
In HTML ids should be unique. I suggest you change your code to something like this:
<div id="div1" >
<input type="text" name="edit1" id="edit1" />
<input type="text" name="edit2" id="edit2" />
</div>
<div id="div2" >
<input type="text" name="edit1" id="edit3" />
<input type="text" name="edit2" id="edit4" />
</div>
Sample Html code
<div id="temp">
F1 <input type="text" value="111"/><br/>
F2 <input type="text" value="222"/><br/>
F3 <input type="text" value="333"/><br/>
Type <select>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<input type="button" value="Go" onclick="getVal()">
</div>
Javascript
function getVal()
{
var test = document.getElementById("temp").getElementsByTagName("input");
alert("Number of Input Elements "+test.length);
for(var i=0;i<test.length;i++)
{
if(test[i].type=="text")
{
alert(test[i].value);
}
}
test = document.getElementById("temp").getElementsByTagName("select");
alert("Select box "+test[0].options[test[0].selectedIndex].text);
}
By providing different tag names we can get all the values from the div.
Unfortunately this is invalid HTML. An ID has to be unique in the whole HTML file.
When you use Javascript's document.getElementById() it depends on the browser, which element it will return, mostly it's the first with a given ID.
You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.