I have an indeterminate number of span and input tags with random IDs.
The user has the ability to change the HTML inside of <span> but not <input>.
It looks like this:
<span id="0">235</span>
<input id="5239aac3" value=235>
<span id="1">12</span>
<input id="123abc2" value=12>
<span id="2">235</span>
<input id="5res345" value=235>
I have put all the IDs of <input> into an array called arrayOfIDs and through JavaScript given all matching <span> tags and Id of the index.
for (var i = 0, l = arrayOfIDs.length; i < l; ++i) {
$('#' + i).on("change", function(){
var txt = $(this).find().text();
var $idval = $(arrayOfIDs[i]);
$idval.val(txt)
}).trigger("change");
}
What I need help with in the code above is how to monitor the change in the innerHTML of all spans and update the corresponding input.
I think that you need to change your first selector from $('#i') to $('#' + i)
otherwise you're selecting the element with the literal id of 'i' , which doesn't exist
Also, is the function firing at all? If so, what output do you get?
Finally, I think that you'll want to change var $idval = $(arrayOfIDs[i]); to var $idval = $('#' + arrayOfIDs[i]);
Related
I have a div in which I render through javascript inputs and text dynamically. I am trying to capture the text of this div (both input values and text).
My first step if to capture the parent div:
let answerWrapper = document.getElementById("typing-answer-wrapper");
The issue now is that using the innerHTML will give me the whole html string with the given tags and using the inerText will give me the text, excluding the tags.
In the following case scenario:
the console inspect is:
What is the way to capture: $2.4 if the inputs have 2 and 4
and $null.null if the inputs are blank.
Any help is welcome
You could iterate over all of the element's child nodes and concatenate their wholeText or value else 'null'. For inputs the wholeText will be undefined. If they have no value we'll return 'null'. Be aware that spaces and line-breaks will also be included so you may want to strip these later (or skip them in the loop) but as a proof of concept see the following example:
var typingAnswerWrapper = document.getElementById("typing-answer-wrapper");
function getVal(){
var nodeList = typingAnswerWrapper.childNodes;
var str = "";
for (var i = 0; i < nodeList.length; i++) {
var item = nodeList[i];
str+=(item.wholeText || item.value || "null");
}
console.log(str);
}
getVal();
//added a delegated change event for demo purposes:
typingAnswerWrapper.addEventListener('change', function(e){
if(e.target.matches("input")){
getVal();
}
});
<div id="typing-answer-wrapper">$<input type="number" value=""/>.<input type="number" value="" />
</div>
Here's how you could do it :
function getValue() {
var parent = document.getElementsByClassName('typing-answer-wrapper')[0],
text = [];
const children = [...parent.getElementsByTagName('input')];
children.forEach((child) => {
if (child.value == '')
text.push("null")
else
text.push(child.value)
});
if (text[0] != "null" && text[1] == "null") text[1] = "00";
document.getElementById('value').innerHTML = "$" + text[0] + "." + text[1]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="typing-answer-wrapper">
$
<input type="number"> .
<input type="number">
</div>
<button onclick="getValue()">get value</button>
<div id="value"></div>
You can fetch input feild values by their respective ids $('#input_feild_1').val() will give the first feild value and similarly $('#input_feild_2').val() for second feild and contruct use them to construct whatever as u wish. As in your case this should work
value_1 = $('#input_feild_1_id').val()
value_2 = $('#input_feild_2_id').val()
you need something like "$ + value_1 + . + value_2"
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>
I have a table- each row has a checkbox of name checkBoxDelete. The id of the check box is unique(used the customer id).
I would like to get all the unique ids that were selected. So, I started by gathering all the elements of the form. Then check if it is a checkbox that is checked. If it is ,then get it's id.
var elLength = document.deleteForm.elements.length;
for (var i=0; i<elLength; i++){
var type = deleteForm.elements[i].type;
if (type=="checkbox" && deleteForm.elements[i].checked){
var rowID=deleteForm.elements[i].id;
checkedIds += rowID + ";" ;
count++;
}
}
However, rowID is always ";".
I believe I am not getting a reference to the checkbox correctly.
Change this var rowID=deleteForm.elements[i].id; to var rowID= document.deleteForm.elements[i].id;
You forgot document before selecting deleteForm
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.
Trying to add the text dynamically to the same span. Have generated an index to the id so that based on index thought to add the text.
This is what i have tried.
Expected output is I need to create one more span with same id but different index and append my array values to the span with index values.
Expected Output Example:
<span id="test-0">test</span>
<span id="test-1">Demo</span>
HTML:
<span id="test-{{$index}}"></span>
JS:
var arr = [{"Name":"test"},{"Name":"Demo"}];
for(var i=0; i<arr.length;i++){
txt = arr[i].Name;
$('#test-'+i).text(txt);
}
Tried Demo:
Demo Link
Try this:
$('#test-'+i).text(txt);
Assign value in text() function
$('#test-'+i).text();
to
$('#test-'+i).text(txt);
You can use string builder, such as:
var arr = [{ "Name": "test" }, { "Name": "Demo" }];
for (var i = 0; i < arr.length; i++) {
txt = arr[i].Name;
document.write("<span id=test-" + i + ">" + txt + "</span>");
}
Try this : You can have a div to add span which will have dynamic id and text from array.
HTML-
<div id="test"></div>
javascript: -
var arr = [{"Name":"test"},{"Name":"Demo"}];
var $text = $('#test');
for(var i=0; i<arr.length;i++){
$text.append('<span id="test-'+i+'">'+arr[i].Name+'</span>');
}
JSFiddle DEMO
The fiddle you had given is wrong. which has been edited as follows.
check fiddle here
var arr = [{"Name":"test"},{"Name":"Demo"}];
for(var i=0; i<arr.length;i++){
//append existing text to new value from array
var txt = $('#test'+i).text() + arr[i].Name;
$('#test'+i).text(txt);
}
If you actually want to use angular, you are going about it all wrong. Angular doesn't play well with html elements added elsewhere, they have to be compiled first so angular can bind to them. In this instance you could use ng-repeat to bind a list to a series of spans:
<span ng-repeat="item in [100, 200, 300, 400]" id="test-{{$index}}">
Index is {{$index}}<br/>
</span>
You also need to include angular in your fiddle and have an element with the ng-app tag (fiddle). Using angular you would also have a named controller and set a property on the scope to your array, but that is outside the bounds if this question.