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();"/>
Related
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.
I added an option within the select element and it does not show in the UI.
I created an option element as a string like
var option = '<option value="' + value + '"> ' + text + '</option>';
option = new DOMParser().parseFromString(option, "text/xml").childNodes[0];
select.insertBefore(option,select[select.length-1]);
This does add the option in its html, but the select element dropdown does not contain the option. Why is that so.
But when I used the following method it works :
var option = document.createElement("option");
option.value = val;
option.text = txt;
select.insertBefore(option,select[select.length-1]);
I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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.
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);
}