I am trying to get value of dynamic generated inputs. Here is my code and what I want actually
Here is my Code:
function activehead_standard(){
var cnt = 4;
for(i=1;i<=cnt;i++){
var active_head = document.getElementById('standard_'.i).value;
}
}
I want to get values of input:
standard_1
standard_2
standard_3
standard_4
but its not getting the value of input through ids I am sure its actually not getting the ids of inputs
use + for concatenation in javascript
function activehead_standard(){
var cnt = 4;
for(i=1;i<=cnt;i++){
var active_head = document.getElementById('standard_'+i).value;
}
}
Related
I have a dynamic table which has the input field in each row. I would like to get the value entered by the user through Javascript. I am able to get the HTML code for the input field 'quantity' but not the value.
Here is the part of the javascript code :
var table = document.getElementById("mactable");
var row_count = table.getElementsByTagName("tr").length;
var grand_total = document.getElementById("grand_total");
var grand_price = 0.00;
for (var i = 1, row; row = table.rows[i]; i++)
{
var price = row.cells[4].innerHTML;
var quantity = row.cells[2].innerHTML;
alert(quantity);
if(isNumber(price))
{
var num = parseFloat(price);
grand_price = grand_price + num;
}
}
Any idea how can it be done ?
Instead of reading table cell innerHTML you can find inner input element and then read its value property:
var quantity = Number(row.cells[2].querySelector('input').value);
Here row.cells[2] is a td element. Using querySelector('input') you can find the first children input.
Also note, that since the value of the field is a string, you might want to cast it to number, for example with Number function.
I have one input field with value : <input id="newfield" value="12345" />
Value of input can be vary and may contain the different length.
I want to replace the whole value if i click on button
<a href="#">button<a>
Value of id="newfield" is dynamic and input come from client side.
It may be 10 , 5 anything.
For example :
use type value - 123123456789
I want it like - xxxxxxxx6789
If user type value - 12345, I want it like - x2345
Note : open for jquery and js both
Convert value to string then loop based on length to replace each character with "X".
// input value "hello world"
var value = $("#input").val().split(""),
newVal = '';
for (var i = 0; i <= value.length - 4; i++) {
newVal += "X";
}
Based on your update, loop again through value array to add last 4 characters.
for (var i = value.length - 4; i <= value.length - 1; i++) {
newVal += value[i];
}
$("#input").val(newVal);
// new value "XXXXXXXXorld"
See it working.
jQuery
$('#mylink').click(function(){
var value = $("#newfield").val();
// make a string with x-characters
var x = new Array(value.length - 3).join('X');
// join this string with the tail of the value, and replace it
$('#newfield').val(x + value.substr(value.length - 4));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="newfield" value="12345"/>
button
Vanilla JS
This uses the same internal code for altering the string, but doesn't use jQuery. Simply add the function to the link:
function changeInputValue() {
// get the value
var value = document.getElementById("newfield").value;
// make a string with x-characters
var x = new Array(value.length - 3).join('X');
// join this string with the tail of the value, and replace it
document.getElementById('newfield').value = x + value.substr(value.length - 4);
}
<input id="newfield" value="12345"/>
button
Assuming your button is:
button
if you are using jquery:
$("#button1").click( function()
{
var old_val = $(#newfield).val();
var last_part = old_val%10000;
var front_part = Array(old_val.length-4+1).join("X"); // to insert N Xs, we require `Array(N+1).join("X")`
$("#newfield").val(front_part + last_part) ;
});
<a href="#" onclick="getValueFromClient()">button<a>
<script>
function getValueFromClient(){
// write ajax call or something which will fetch value from client and assign back to input field.
var valueFromClient=10; // write code to fetch value
$("#newfield").val(valueFromClient);
}
</script>
I need to get the number only from an attribute (The number is dynamic). The button/anchor looks like this:
Delete Dish
The part I need to dissect is this bit 'bc_inventorybundle_menu_product_0' I only want the number, for use in another function (Delete a LI with an ID of menuitem0_dish)
The code I use for selecting ID's elsewhere is:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("id").substring((prefix.length));
return num;
}
It works great on ID's but I cant seem to get it to work for Attributes instead of ID's
So User clicks delete button bc_inventorybundle_menu_product_0 then jQuery removes the < li id="menuitem0_dish">
I can't add an ID to the button so I have to use the attribute of the button. As I'm sure you can tell I'm a complete noob when it comes to JS/JQuery.
EDIT
Having read all the answers I feel I may need to elaborate a little.
I think the biggest issue is registering when the Button/Anchor is clicked.
What I currently have is this, which I know must be wrong:
$(document).on('click', 'data("field")', function(event) {
deleteDish(this);
});
function getbutNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var butnum = element.data("field").substring(prefix.length); //Changed as per suggestions
return butnum;
}
function deleteDish(field) {
var numbut = getbutNum();
//Delete the UL/LI
console.log("Num But" + numbut);
}
Asides from all else this gives me an error of 'unrecognized expression: data("field")'
Have you tried selecting your actual data attribute:
var num = element.attr("data-field").substring(prefix.length);
Or:
var num = element.data("field").substring(prefix.length);
EDIT
First add a class to your anchor element (I'm going under the assumption that you have more than one of these):
Delete Dish
Then:
$(".delete-dish").on("click", function (e) {
e.preventDefault();
var fieldData = $(this).data("field"),
num = fieldData.substring(fieldData.lastIndexOf("_") + 1);
console.log("Num But" + num);
});
Here is a fiddle to demonstrate
Using the attribute name that contains your input should work:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("data-field").substring((prefix.length));
return num;
}
http://jsfiddle.net/zf3hmo4q/
Considering you want to parse attributes with "data-*" name:
function getNum(element, dataName, dataPrefix) {
var num = element.data(dataName).replace(dataPrefix, "");
return num;
}
console.log(getNum($(".btn"), "field", "bc_inventorybundle_menu_product_"));
Maybe something like this?
var getNumberFromAttribute = function(id, field) {
var field = $(id).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
Here's a jsfiddle http://jsfiddle.net/o6go79cL/
UPDATE
You could just pass in the element. The only purpose of the id was to select the object. So you could also just do:
var getNumberFromAttribute = function(elm, field) {
var field = $(elm).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
number = getNumberFromAttribute(anchorTag, "field");
I have a listbox that I am trying to read through all the data in it and put those values in a textbox. I thought I this would use a for loop but it only runs once and then quits.
var listbox = $('#<%=listBox.ClientID%>');
for (var count = 0 ; count <= $('#<%=listBox.ClientID%>').length; count++) {
var existing = $('#<%=stringTextBox.ClientID%>').val();
var value = listbox[count].value;
document.getElementById("<%=stringTextBox.ClientID%>").value = "," + value + existing
}
First: #<%=listBox.ClientID%> is an selector by ID. The idee of IDs is that there is always at most one element with this ID.
Second: var value = should be something like var value = $(<listboxselector>).get(count).val()
Do you have to do anything special while passing in a dynamically created string as a clientID for document.getElementById?
I have a asp:gridview control that has a textbox column and a checkbox column. I added an onclick event to the checkboxes to set the textbox value of that row to the max value of all checked rows +1. I pass in the IDs of the grid and the controls of the row that was selected. I can getElementByID fine for these controls, but When I dynamically build the IDs of the other controls, I keep getting null, even though I know that the IDs are correct. My code is bellow.
function SetPriority(cbID, tbID, gridID) {
var cb = document.getElementById(cbID);
if (cb.checked) {
var tb = document.getElementById(tbID);
var grid = document.getElementById(gridID);
var maxv = 0;
for (var i = 0; i < grid.rows.length; i++) {
var indexID = 102 + i;
var cbClientID = 'LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ct' + indexID + '_chkGroup';
var tbClientID = 'LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ct' + indexID + '_txtPriority';
console.log("row" + i);
//just for example of how it should be working
console.log(cbID);
var cbx = document.getElementById(cbID);
console.log(cbx);
//get row checkbox
console.log(cbClientID);
var thisCB = document.getElementById(cbClientID);
console.log(thisCB);
//get row textbox
var thisTB = document.getElementById(tbClientID);
console.log(thisTB);
if (thisCB) {
if (thisCB.type == "checkbox") {
if (thisCB.checked) {
if (thisTB.value > maxv)
maxv = thisTB.value;
}
}
}
}
tb.value = parseInt(maxv) + 1;
}
}
Here is how its showing up in the console, where you can see the IDs for the first row are the same
For Those wondering about How I am calling the function, I am adding it on to a checkbox in a .net gridview control on row databind. It renders as follows:
<input id="LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ctl02_chkGroup" type="checkbox" name="LeaveInfo$pnlMain$wgbLeaveSummary$gridSubmitted$ctl02$chkGroup" onclick="javascript:SetPriority('LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ctl02_chkGroup','LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ctl02_txtPriority','LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted');">
The vb .net code to add the function is this...(on-_RowDataBound)
Dim chk As CheckBox = CType(e.Row.FindControl("chkGroup"), CheckBox)
Dim tb As TextBox = CType(e.Row.FindControl("txtPriority"), TextBox)
chk.Attributes.Add("onclick", String.Format("javascript:SetPriority('{0}','{1}','{2}');", chk.ClientID, tb.ClientID, gridSubmitted.ClientID))
No, you don't have to do anything special when dynamically building a string. A string in javascript is the same string whether it was built dynamically or specified directly in your code. If document.getElementById() is not working, then one of the following is likely the cause:
Your string isn't what you think it is so it doesn't match the target id.
Your DOM id isn't what you think it is.
You have multiple elements with the same id (not likely here because you won't get null)
You are calling getElementById() before the DOM is ready or before the desired elements have been added to the DOM.
In this case, it seems more likely that 1) or 2) are the issues here, but you don't show us any context to know whether 4) could be the problem.
Not 100% sure, but I think it could be a context issue. Try this:
function ( id ) {
var ID = document.getElementById;
this.id = id;
this.newvar = ID.call( document, this.id );
...
}
Also, this question may help you — it has a good explanation on context and assigning a var to getElementById Why can't I directly assign document.getElementById to a different function?
I couldnt figure out why my IDs that seemed identical were not. I will leave this question open for anyone to add insight on how to remedy this. I ended up just getting my elements by cell and not by ID.
function SetPriority(cbID, tbID, gridID) {
var cb = document.getElementById(cbID);
if (cb.checked) {
var tb = document.getElementById(tbID);
var grid = document.getElementById(gridID);
var maxv = 0;
if (grid.rows.length > 0) {
for (row = 1; row < grid.rows.length; row++) {
var thisCB = grid.rows[row].cells[5].childNodes[1];
if (thisCB == cb) {
continue;
}
var thisTB = grid.rows[row].cells[6].childNodes[1];
if (thisCB.type == "checkbox") {
if (thisCB.checked) {
if (thisTB.value > maxv)
maxv = thisTB.value;
}
}
}
}
tb.value = parseInt(maxv) + 1;
}
}