Pull first instance of input and add id via JS - javascript

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>

Related

How to set values in dynamically created text boxes

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.

Monitor HTML and add changes to an input value

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]);

Print dynamic Text box value using JQuery

I have a scenario like
for(int i = 0; i < 10; i++)
{
<input type = "text" id="test"+i value="" onchange="getValue(i)">
}
I want to print selected text box value using jquery. I tried below code,....
function getValue(id)
{
var value = $("#test"+id).val();
alert(value);
}
Some how the above code is not working.
if i tried like var value = document.getElementById("test"+id); then it is working.
jsBin demo
var inp = ''; // String will hold all inputs
for(var i=0; i<10; i++){
inp += '<input type="text" id="test'+i+'" value="" />'; // Generate 10 inputs
}
$('body').append( inp ); // All inputs to HTML
$('input[id^="test"]').on('input', function(){
console.log( this.value );
});
You can't just drop raw HTML inside of a JavaScript loop like that. You have to set a string or create an element and append it to the DOM.
"getValue(i)" is a string. The "i" is not the variable i, it is literally a string with the letter i. If you want to concatenate strings and variables you have to do so like this:
var name = "Neil";
var greeting = "Hi, my name is " + name + ", nice to meet you!";

Dynamically Load Div Elements and Assign IDs

I understand how to dynamically load HTML, I am having trouble understanding how I load it, assign, and keep track of IDs for elements inside the loaded div.
This is my main block
<div id="add-equip-container">
<div id="add-equip-content">
</div>
<button id="add-equipment">Add More Equipment</button>
<button id="submit-equipment">Submit Equipment</button>
</div>
Now, every time add-equipment is clicked, I want to load the following block into add-equip-content.
<div class="add-equip-form">
<input id="?" type="text" placeholder="Equipment Description..."/></br>
<input id="?" type="text" placeholder="Equipment Number"/></br>
<input id="?" type="text" placeholder="Other Stuff..."/></br>
</div>
Each block would be inserted beneath the previous one loaded. I have no idea how to assign and keep track of the various IDs that will be dished out during this operation. I would love a solution that does not involve jQuery. I am trying to lean vanilla JavaScript before I get into frameworks.
I am sure there may be a question or blog or something on this already, but I just don't know the best keywords to search for. Any time I use "Dynamically Load HTML" in the search keywords, all I get is AJAX Tutorial results.
Thanks in advance for any help!
One solution would be not actually load the HTML, but to create it via Javascript. This would be useful in your case as you are adding the same code to the page, only with different ID's. I would write a function like this:
var form_index = 0;
//elem is the element you are appending to.
function addForm(elem) {
//create the container
var form_container = document.createElement("div");
form_container.className = "add-equip-form";
//description input
var desc = document.createElement('input');
desc.id = "equip-desc-" + form_index;
desc.type = "text";
desc.placeholder = "Equipment Description...";
//Equipment number input
var num = document.createElement('input');
num.id = "equip-num-" + form_index;
num.type = "text";
num.placeholder = "Equipment Number";
//Other
var other = document.createElement('input');
other.id = "equip-other-" + form_index;
other.type = "text";
desc.placeholder = "Other Stuff...";
//append inputs
form_container.appendChild(desc);
form_container.appendChild(num);
form_container.appendChild(other);
//append form
elem.appendChild(form_container);
form_index++;
}
Then, to access your created ID's, all you need to know is the index of the containing div within your parent elem. See here for a javascript solution. Once you have the index, getting the form data is as easy as using your index to query based on ID's.
This should do it. You may or may not need to do the elements.push(content) if you don't need to refer back to these elements in an array. Could just iterate a counter instead.
var add_equip_content = document.getElementById('add-equip-content'),
add_equip_btn = document.getElementById('add-equipment'),
elements = [];
add_equip_btn.addEventListener('click', addEquipment, true);
function addEquipment(event){
var content = document.createElement('div'),
html = '';
content.className = 'add-equip-form';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Description..."/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Equipment Number"/></br>';
html += '<input id="equip_' + elements.length + '" type="text" placeholder="Other Stuff..."/></br>';
content.innerHTML = html;
add_equip_content.appendChild(content);
elements.push(content);
}

Javascript to get the div info

I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
​$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});​​​​​​​​
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.

Categories

Resources