Here i'm trying to append some text to an input field but everytime the old value gets replaced with new value.
HTML
<input type="text" id="taginput" class="input" name="tags">
Javascript
function update(i){
document.getElementById('taginput').value = i.innerHTML;
}
no jquery please.
You have to get the old value first, and then add to it
function update(i){
var elem = document.getElementById('taginput');
var old = elem.value;
elem.value = old + i.innerHTML;
}
or you could add it to with += directly
elem.value += i.innerHTML;
function update(i){
let elem = document.getElementById('taginput');
elem.value = elem.value + i.innerHtml;
// Or elem.value += i.innerHtml;
// elem.value = elem.value.concat(i.innerHtml)
}
<html>
<head>
</head>
<body>
<input id="my_msg" type="text">
</body>
<script>
document.getElementById('my_msg').value = "text-value";
</script>
</html>
document.getElementById('my_msg').value = "text-value";
Use above script to append 'text-value' to input field.
Thanks
Related
Having trouble getting the a label dynamically assigned to a radio button. all of the code is working except the innerHTML. Cannot spot why. Thanks in advance for any help.
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
</form>
<br>
<button onclick="addRadio()">Add radio buttons!</button>
<script>
// This function will add a new Radio buttons to the above
count = 0;
function addRadio()
{
count++;
//Create input type
var myRadio = document.createElement("input");
var myName = document.createElement("testRadio");
var myBreak = document.createElement("br");
var myLabel = document.createElement("label");
var labelMessage = "Radio Button: " + count;
var labelId = "l" + count;
myRadio.setAttribute("type", "radio");
myRadio.setAttribute("name", "testRadio");
myRadio.setAttribute("value", "Radio Button: " + count);
myLabel.setAttribute("for", labelId);
myRadio.setAttribute("id", labelId);
document.getElementById('myForm').appendChild(myRadio);
document.getElementById('myForm').appendChild(myLabel);
document.getElementById('myForm').appendChild(myBreak);
document.getElementById('labelId').innerHTML = 'labelMessage';
}
</script>
</body>
</html>
The label element might not be inserted by the next line itself. It is better to do
myLabel.innerHTML = 'labelMessage';
As you have the element already in a variable.
There is a tiny error in the code.
Before the .innerHTML you get the element by id 'labelId' as a string.
You need to select with the labelID as a var so:
document.querySelector(`label[for="${labelId}"]`).innerHTML = labelMessage;
I am very new to javascripts and trying to create a dynamic html form where there are multiple button, and each button click map to a corresponding form input. Here is my code:
<html>
<head>
<title>Create Group</title>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function(){
$("#generate_form").click(function(){
var number = document.getElementById("number_of_groups").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
var i;
for (i=1;i<=number;i++){
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
}
})
});
</script>
</head>
<body>
<h2>Create some group(s)</h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"/>
</body>
</html>`
So, the user would input number of groups to create and click 'Go' button, then the code should dynamically generate the form with the number the user choose. Each group of the form includes a input textbox and a 'Generate' button. When the button is clicked, the input textbox will show "hello world". However, the "hello world" only show up in the last input textbox no matter which 'Generate' button I click. So I changed the onclick function of the button to:
button.onclick = function(){ alert(thisID);};
Then I found that thisID is always the id of the last input textbox no matter which 'Generate' button I click. I guess that is because the binding of the click event does not happen till the script is done when 'thisID' would always be its latest value.
Would anyone please help me to realize the functionality I want? Thank you very much!
You would need to wrap the code within the for loop in a separate function, passing in the value of i as a parameter. This would create a closure, creating a new execution scope for your code. Otherwise what is happening is that your var is being hoisted, and is not exclusive to each iteration of the for loop, so your DOM is reflecting only the last value it was assigned.
for (i=1;i<=number;i++){
(function (i) {
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
})(i);
}
You can check out an article on closures here:
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
EDIT: As one of your commenters mentioned, you can also set your vars to 'let' to achieve a similar effect. This is because let scopes the variable to the current code block, rather than being hoisted to the scope of the function, so each for loop iteration has a private let variable. It is still recommended to get a good understanding of closures and how they work, however.
Since you are already using JQuery, you can reduce some of the logic.
Let me know if this helps-
<html>
<head>
<title>Create Group</title>
</head>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(()=>{
var txtGroup='<input type="text" id="txt_group_{0}" value="">';
var btnGroup='<button id="btn_group_{0}" type="button">Click Me</button>';
var container=$('#container');
$('#generate_form').click((e)=>{
var groupCount=parseInt($('#number_of_groups').val());
var idToStart=$('#container').children('div').length+1;
for(let i=idToStart;i< idToStart+groupCount;i++){
var divGroup=`<div id="div_group_${i}">`+
txtGroup.replace('{0}',i)+
btnGroup.replace('{0}',i)+`</div>`;
container.append(divGroup);
$('#btn_group_'+i).on('click',(e)=>{
console.log('#txt_group_'+i);
$('#txt_group_'+i).val('Hello World');
});
}
});
});
</script>
<body>
<h2></h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"></div>
</body>
</html>
what is wrong with the code? i have to get the text from the input text box after clicking on submit button, the input text value must be shown in paragraph.
<html>
<body>
<p id="demo"></p>
<br>
<input id="myList" type="text">
<input type="button" value="Try it" onclick="myFunction()"></button>
<script>
function myFunction()
{
var x = document.getElementById("myList");
var txt = "Welcome ";
for (var i=0;i<x.length;i++)
{
txt = txt + x.elements[i].id + "br";
}
document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>
You would want to use this code
document.getElementById('myList').value;
it will grab the value from the input box element.
Check here a demo
Check here no need to loop all the elements
You just need a id of the element so why are you looping it ?
Here is the source code of it
This is the javascript code looks like
function myFunction()
{
var x = document.getElementById("myList");
var txt = "Welcome ";
txt = txt + x.value + "br";
document.getElementById("demo").innerHTML=txt;
}
You want a value from the element so you have to take a value you can see in the functiont
x.value so it will retrive the value from the element and then your function will work i hope this will help you
There are two ways to fix it:
[1] Change x.length to x.value.length and x.elements to x.value.elements
The fiddle
[2] Change var x = document.getElementById("myList"); to var x = document.getElementById("myList").value;
And the fiddle, why not?
A text box has no property length, so I think you are referencing to its text? That's what this fix will do. (Also, it's better practice to use method 2.)
<html>
<body>
<p id="demo"></p>
<br>
<input id="myList" type="text">
<input type="button" value="Try it" onclick="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("myList").value;
alert(x);
var txt = "Welcome ";
for (var i = 0; i < x.length; i++) {
txt = txt + x.charAt(i) + "<br />";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
loop??? I didn't understand its very simple try this.
<html>
<body>
<p id="demo"></p><br>
<input id="myList" type="text">
<input type="button" value="Try it" onclick="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("myList");
var txt = "Welcome " + x.value;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
OR
var x = document.getElementById("myList").value;
var txt = "Welcome " + x;
You have to take the "myList" id's value and then assign it to innerHTML of tag which could be done as follows :
<html>
<body>
<p id="demo"></p>
<br>
<form>
<input id="myList" type="text">
<input type="button" value="Try it" onclick="myFunction()"/>
</form>
<script>
function myFunction()
{
var txt = "Welcome";
var x = document.getElementById("myList").value;
txt = txt +" "+x;
document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>
I'm trying to make multiple buttons that when clicked they add tags like <p></p> and <b></b> to a text-field. I have already figured out how to make it work like this:
<script>
function addtxt(input) {
var obj=document.getElementById(input)
obj.value+="<p></p>"
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body')">
but instead of having multiple scripts for every different button, I'd like to know if there is a way of the JS use the element value as obj.value. Is it possible?
EDIT: i found this other code online that's even better, how can i make this new code use the element value, is there any way?
function boldText(textAreaId, link)
{
var browser=navigator.appName
var b_version=navigator.appVersion
if (browser=="Microsoft Internet Explorer" && b_version>='4')
{
var str = document.selection.createRange().text;
document.getElementById(textAreaId).focus();
var sel = document.selection.createRange();
sel.text = "<b>" + str + "</b>";
return;
}
field = document.getElementById(textAreaId);
startPos = field.selectionStart;
endPos = field.selectionEnd;
before = field.value.substr(0, startPos);
selected = field.value.substr(field.selectionStart, (field.selectionEnd - field.selectionStart));
after = field.value.substr(field.selectionEnd, (field.value.length - field.selectionEnd));
field.value = before + "<b>" + selected + "</b>" + after;
}
You may pass this to your onclick handler, and then access it's value within your function:
<script>
function addtxt(input, button) {
var obj=document.getElementById(input);
obj.value+=button.value;
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body', this)">
<input type="button" value="<b></b>" onclick="addtxt('body', this)">
Here is an example with a specific div that receives the code javascript produces.
I don't recomend adding it to a div with id body, because that word is reserved for html structural elements, so I called the destination div "addHere".
Javascript
function addtxt(e) {
console.log(e)
var dest = document.getElementById("addHere");
dest.innerHTML = e.value;
}
HTML
<input type="button" value="<p>Text</p>" onclick="addtxt(this)">
<div id="addHere"></div>
fiddle here
Hi want to store what user input into the textbox into my javascript var to be passed to my external PHP page,
I can pass the variable if i just define a value like mySite= 22 but not from what user enters into the text box.
Please help me to get access to the texbox.value
<form method="post" action="" onsubmit="submitFun(this)">
<input type="text" name="order_IDsearch" id="order_IDsearch"onBlur="javascript:setmysite(this);">
<input type="submit" />
</form>
<script type="text/javascript">
var mySite = '';
function setmysite(v1) {
var parent = document.getElementById('list');
var element = parent.GetElementsByTagName('order_IDsearch')[0];
mySite = element;
}
function submitFun(f1) {
t = './get_order.php?s=' + mySite;
t = encodeURI (t);
f1.action = t;
f1.submit();
return true;
}
You can try document.getElementById('order_IDsearch').value;