I'm using JavaScript to dynamically add rows to a table, I create some textboxes in each row, I've added an onkeyup event to one of my textboxes:
var myTotal = "1";
var spanTotal = document.createElement("span");
spanTotal.innerHTML = "<input style=\"width:50px\" type=\"text\" name=\"total\" value=" + myTotal + ">";
spanCount.onkeyup = function ()
{
alert(spanTotal.innerHTML);
};
then I add this span (which is rendered as an HTML textbox) to my table row. I want to have value of my dynamically created textbox, but whenever I change this textbox, initial value of this textbox is displayed in alert box (i.e. 1). Initial value of this textbox is "1", but when I change it (for instance type a 0 in textbox), again "1" is displyaed in alert box. I want to have value of my dynamically created textbox, should I give an ID to my span? how should I define spanCount.onkeyup function? where should it be defined so that I can have exact value of this textbox?
I created a jsFiddle. You can get value of input box using childNodes. There are other problems in code you were using spanCount istead of spanTotal.
Modified code:
var myTotal = "1";
var spanTotal = document.createElement("span");
spanTotal.innerHTML = "<input style=\"width:50px\" type=\"text\" name=\"total\" value=" + myTotal + ">";
document.body.appendChild(spanTotal);
spanTotal.onkeyup = function() {
alert(spanTotal.childNodes[0].value);
};
Below modified code maybe can solve your problem:
var myTotal = 1;
/* object creation */
var span = document.createElement('span');
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', 'total');
input.setAttribute('style', 'width:50px;');
input.setAttribute('value', myTotal);
// append each object to respective container
span.appendChild(input);
document.appendChild(span);
/* event handler */
input.onkeyup = function(){
alert(this.value);
}
Related
Im doing a dynamic text box with javascript. But when I execute my button, the value I alredy inserted are erased. So like if I have one textbox and type something on it, when I execute the button to create another textbox it erase all I had type on the 1st one, and create the other one.
I understand why it is happening, but I dont know if there is a way to hold the value, and pass to the "new" div.
<script language="javascript">
var x = 1;
function Button()
{
my_div.innerHTML = my_div.innerHTML +"<label for='variation'>Carro " + x +": </label>" + "<input type='text' name='xcar"+ x +"'>"
x++;
}
</script>
So the problem as I said before was that the my_div.innterHTML was replacing himself and losing the values.
<script language="javascript">
window.onload = function () {
var createTextbox = function () {
var x = 1,
container = document.getElementById('my_div');
return function () {
var div = document.createElement('div');
input = document.createElement('input');
input.type= "text";
input.name = "xtext" + x;
div.appendChild(input);
container.appendChild(div);
x++;
}
}();
document.getElementById('createButton').onclick = createTextbox;
</script>
<input class="carbutton" type="button" value="+ Carro" id="createButton">
I just used this code instead.
I am trying to replace an input box with Vanilla JS. Currently I am using jquery to do this like so.
column.replaceWith("<select id='" + column[0].id + "' name='" + column[0].id + "' class='" + column[0].className + "'></select>");
I am refactoring all my code into Vanilla JS and this is the last thing I need to do. I have done the document.createElement('select'); and that creates the <select></select> element. I then tried to do;
newEl.innerHTML += '<select id="selBidReceivedIsPM" name="selBidReceivedIsPM">'
+ '<option value="0">AM</option>'
+ '<option value="1">PM</option>';
,
but this doesn't create the id or name. I've been googling and trying things for the last 3 hours and need some help figuring this out.
html:
<label for="columnA5"></label>
<input
type="number"
id="columnA5"
name="columnA5"
class="columnA"
step="any"
>
Something like this should work to create select with options having value and innerHTML.
var select = document.createElement('select');
select.id="selBidReceivedIsPM"
select.name="selBidReceivedIsPM"
var val=2;
var time=["AM","PM"];
for (var i = 0; i<val; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = time[i];
select.appendChild(opt);
}
console.log(select)
I think, if DOM element is not created by javascript but rendered You can't "delete" it (in Your case input type="number"...).
You can "replace" it by "hiding" input and place select element on "his" place.
There is example, try it :
function replaceEle() {
var txt=document.getElementById('columnA5');
/*
or You can use querySelectorAll :
var txt=document.querySelectorAll('input[type="number"]');
then You'll get all textboxes in page, and then You have to use for loop
*/
var sel=document.createElement('select'); //create select element
sel.id='selBidReceivedIsPM';
sel.setAttribute('onchange','alert(this.value)');
/*show selected value, or instead alert You can type some JS
function, what gonna do when option is changed */
var opt=document.createElement('option'); //create option element
opt.value=0;opt.innerHTML='AM';
sel.appendChild(opt); //add option element into select element
opt=document.createElement('option');
opt.value=1; opt.innerHTML='PM';
sel.appendChild(opt);
sel.selectedIndex=0; //set default selected value
txt.style.display='none'; //hide input element
txt.parentNode.insertBefore(sel, txt); //insert select element just before input,
}
<input type="number" id="columnA5" value=""/><br>
<input type="button" value="Replace it" onclick="replaceEle();"/>
Note: Willing to use jQuery, whatever is easier.
I have a form which when submitted, creates a checkbox input. The text of the checkbox should be equal to that of another text input when the form is submitted.
The checkbox is created as expected when I submit the form but it is blank and doesn't contain the text from the corresponding text area.
For a checkbox i'm not sure if I should be using .text, .innerhtml, .val etc and the previous questions I saw on here seemed unnecessarily complicated.
HTML:
<div id="listContainer">
<form id="listForm">
<input type="submit" value="Add">
<input id="listInput" class="textarea" placeholder="Add your list item here, then click submit.">
<div id="checkboxContainer">
</div>
</form>
</div>
JS:
//ADD LIST ITEM
$("#listForm").submit(function(ev) {
ev.preventDefault();
if ($("#listInput").val() == "") {
alert("Please enter the item name, then click 'Add'.");
} else {
listCount++;
var input = $("#listInput").val();
console.log("List Count: " + listCount);
console.log(input);
var cb = document.createElement('input');
cb.id = 'input' + listCount;
cb.type = 'checkbox';
document.getElementById("checkboxContainer").appendChild(cb);
var label = document.createElement('label');
label.id = 'label' + listCount;
$("#label" + listCount).attr("for", "input" + listCount).html(input);
document.getElementById("checkboxContainer").appendChild(label);
//Store the list count
localStorage.setItem("listCount", listCount);
//Store the list title
localStorage.setItem("input" + listCount, input); //"Note " + noteCount + ": " +
this.submit();
}
});
var label = document.createElement('label');
label.id = 'label' + listCount;
$("#label" + listCount).attr("for", "input" + listCount).html(input);
document.getElementById("checkboxContainer").appendChild(label);
These four lines can be cleaned up and fixed. The issue here is quite simple, however your constant back-and-forth between jQuery and plain JS makes things very difficult to read. I would suggest writing DOM manipulation in one or the other, but never both.
The error here is on the third line, which uses the selector $("label" + listCount). This selector will look for this element on the page, however you've only created the element - you haven't added it to the page yet.
Let's correct this and rewrite it in jQuery:
$("<label />") //create new label
.attr("id", "label" + listCount) //set ID
.attr("for", "input" + listCount) //set For
.html(input) //set contents
.appendTo("#checkboxContainer"); //add to checkbox container
Consider using the example above to rewrite your checkbox creation as well, that way you can avoid the mixture of jQuery/plain JS.
How can I set an input field ID when creating them dynamically when the user clicks a button.
I have a text field and a combo box pair which will be created on click. So every time the user clicks and creates one pair, I need to assign them unique IDs so that these value pairs can be saved to an array for later retrieval.
function createattr() {
var input = document.createElement("input");
input.type = "text";
input.placeholder="Attribute name";
input.className = "attr-textfield-style";
inputval.appendChild(input);
//Display the drop down menu
var newDiv=document.createElement('div');
var html = '<select>', attrtypes = typeGenerate(), i;
for(i = 0; i < attrtypes.length; i++) {
html += "<option value='"+attrtypes[i]+"'>"+attrtypes[i]+"</option>";
}
html += '</select>';
newDiv.className="attr-combobox-style";
newDiv.innerHTML= html;
inputval.appendChild(newDiv);
}
Solved it. It was this one simple line.Just wanted to share this for future references.
input.id="attr"+attrID;
with attrID being declared as a global variable that is incremented before the function ends so that each input field is assigned a unique ID
I just added the 'attr' string to an ID so that the combobox selected along with this text field will have the same numeral (i.e. One pair-> text field id- attr3, combobox- type3. The next pair will have -> text field id- attr4, combobox- type4)
if the elements never get deleted, you could count existing elements and give ID accordingly, like:
var newId = document.getElementsByClassName('attr-combobox-style').length;
input.id = 'attr' + newId;
Or you could use timestamp, it will be absolutely unique:
input.id = 'attr' + new Date().getTime();
In my app I am creating some dynamic textboxes by clicking an add button. We can put some values and time also. Now my need is that when the page loads, I want a given number of textboxes to be created and populated by a set of values. I am able to create the text boxes onload but cannot set the values. Here I am giving a fiddle where I have created my functionality. How can I set some values dynamically? Here is the fiddle MYFIDDLE
And also I want timepicker function in those onload created boxes.
function getTextBoxAfterValiddation(val){
var str_array = ['jeet','chatterjee'];
var randomId = '\''+"#interviewName"+val+'\'';
var nameId = "interviewName"+val+"";
var allNames = str_array.replace(/((\[)|(\]))/g,"");
alert(randomId)
$(randomId).val(arr[val]);
return '<input class="txt1" name = "DynamicTextBox" type="text" id = "'+nameId+'"/>';
}
for(var i = 0; i < 4; i++){
var div = $("<div />");
div.html(getTextBoxAfterValiddation(i));
$("#TextBoxContainer").append(div);
}
When you dynamically generate each element increment a counter and use that value as the elements id. Then you can put html or values into each element using jquery. In the example below every time i click a button with id "addphys" i append a new div on. Later i can grab values from each div because i know the count and each new div id is phys1, phys2, phys3...
var numphys = 0;
$("#addphys").click(function(){
$("#test").append("<div class=\"addedphys\"><p id=\"phys"+ numphys + "\"><p><label>Physician Username:</label><input type=\"text\" class=\"inputbox\" id=\"physusername" + numphys + "\" name=\"pass\"></p><p><label>Physician Password:</label><input type=\"text\" class=\"inputbox\" id=\"physpassword" + numphys + "\" name=\"pass\"></p></p></div>");
numphys += 1;
});
Hope that helps.