How to select elements by name using RegEx - javascript

I have a table with some records, In each row tr I have two Textbox in two TD,
All textboxes don't have Id and Class, They just have a Name, Their Names Are like below
PurchaseDetails[some number].Quantity
PurchaseDetails[some number].PurchasePrice
Like:
PurchaseDetails[1457160526936].Quantity
PurchaseDetails[1457160526936].PurchasePrice
I use below codes but doesn't work:
var ProductQuantity = $(this).find("input[name=PurchaseDetails[/^[0-9]+$/].Quantity]").val();
var ProductPurchase = $(this).find("input[name=PurchaseDetails[/^[0-9]+$/].PurchasePrice]").val();
my complete html code is :
<tr >
<td><input type="text" class="form-control" name="PurchaseDetails[1457161853893].Quantity" ></td>
<td><input type="text" class="form-control" name="PurchaseDetails[1457161853893].PurchasePrice" ></td>
</tr>

If there is only one element with that prefix and suffix in the current context($(this)), attribute starts with selector and attribute ends with selector can be used.
$(this)
.find('input[name^="PurchaseDetails"][name$="Quantity"]').val();

You can use filter() for filtering using regex
// replace `$('input')` to `$(this).find('input')` to avoid searching in global context
var ProductQuantity = $("input").filter(function() {
return /^PurchaseDetails\[\d+\]\.Quantity$/.test(this.name);
}).val();
var ProductPurchasePrice = $("input").filter(function() {
return /^PurchaseDetails\[\d+\]\.PurchasePrice$/.test(this.name);
}).val();
console.log(ProductQuantity, ProductPurchasePrice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="PurchaseDetails[1457160526936].Quantity" value=1 />
<input name="PurchaseDetails[1457160526936].PurchasePrice" value=2 />

Related

set value to texboxes with same name

I have a number of textboxe as
<td><input type="text" class="textbox" name="txtname[]" id="txtname[]" /></td>
<td><input type="text" class="textbox" name="txtfname[]" id= "txtfname[]" /></td>
<td><input type="text" class="textbox" name="txtmname[]" id="txtmname[]" /></td>
so i can have a table like form to enter values with number of rows of these textboxes.i need to set values for this texboxes.i have the row number which i need to set..but how can i get one row of these textboxes to set the value using id??
This is my form. number of rows are dynamic thats y i name them like that.i need to set a value for a circled textbox.How do i do it?
Your question is indeed pretty unclear but I assume that you just want to be able to manage component with dynamic id.
It is not a problem as you can simply use a variable for your id (it has to be a string at the end) but remember that your id has to remain unique.
Your algorythm could be :
for(i=0;i<txtname.length;i++) {
form+="<td><input type='text' class='textbox' name='txtname' id='txtname"+i+"' /></td>"
}
As per Rule, "Id" should be unique across the current page,
So you have to use "class" in case of more then one DOM element.
so you can do this like:
var row =$(".textbox")
row[0].value="FirstName"
row[1].value="MiddleName";
row[2].value="lastName"
if you have 4 row and dynamic(many) column:
var row = new Array(4);
for(loop to row length){
row[loop] = $(".textbox"+loop);//textbox0,textbox1,textbox2...
}
for accessing the value use row[column_index][row_index];
ex. row[0][2].value give you MiddleName input field value
I hope you get this short explanation
As many have said your id attribute in html has to be unique so the use of an array name is not proper here please see here https://www.w3.org/TR/REC-html40/types.html#type-name.
Since this is table columns are generated dynamically I would recommend a naming convention on the table and then use that to find the current input you want. I have no idea how you access this information but my example below does this
Get table we are using.
Get the row for the index you want (Not sure how you determine this) in a comment you had '$(''#textbox[0]").val();' this index would be the 0...
On that row find the input by name and get its value.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<table id="datesheet">
<tr>
<td><input type="text" class="textbox" name="txtname[]" value="test0"/></td>
<td><input type="text" class="textbox" name="txtfname[]"/></td>
<td><input type="text" class="textbox" name="txtmname[]"/></td>
</tr>
<tr>
<td><input type="text" class="textbox" name="txtname[]" value="test1"/></td>
<td><input type="text" class="textbox" name="txtfname[]"/></td>
<td><input type="text" class="textbox" name="txtmname[]"/></td>
</tr>
<tr>
<td><input type="text" class="textbox" name="txtname[]" value="test2"/></td>
<td><input type="text" class="textbox" name="txtfname[]"/></td>
<td><input type="text" class="textbox" name="txtmname[]"/></td>
</tr>
</table>
</body>
</html>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
//Use an id on the table and get its rows
let rows = $("#datesheet tr");
//Now find the row you want
let row_id = 1; // Not sure how you get this value.
let current_row = rows[row_id];
//Get the input you wants value
let input_data = $(current_row).find("td input[name='txtname[]']").val()
//Not sure what should be the same now.
//If it is the other tds in this row then use selector above and set with val.
//If is is other rows input with the same name... That would be a bit involved and I would need some time.
//This is what other mean by unclear.
alert(input_data);
</script>

How to load the datapicker of the following context inside <td> </td>?

In he above code, I would like to add datepicker of input field which contains id as datepicker.
For this purpose i used the following js code in document.ready() func
$("tbody#docTab").click(function() {
var row = $(this).closest('tr');
row.find('#datepicker').removeClass('hasDatepicker').datepicker();
});
But i does not appear the datepicker while onclick the input field, What i have missed on this code?
Advanced thanks.
assign unique id to each element in html, here ids are being duplicated - instead of assigning same id to multiple inputbox - I would suggest add class "datepicker" to every input to whom you want to add datepicker:
<td>
<input type="text" name="sdate[]" class="datepicker" value="0000-00-00" />
</td>
<td>
<input type="text" name="edate[]" class="datepicker" value="0000-00-00" />
</td>
and in jquery:
$("tbody#docTab").click(function({
$('.datepicker').removeClass('hasDatepicker').datepicker(); // you can directly add datepicker using its class name
});
You can NOT have 2 element with same ID.
Please try to use class for your input
<input type="text" name="sdate[]" class="datepicker" value="0000-00-00">
js update:
$("tbody#docTab").click(function() {
var row = $(this).closest('tr');
row.find('.datepicker').removeClass('hasDatepicker').datepicker();
});

function for keypress event not triggered when typing too fast

FIDDLE DEMO
var oldValue;
$(document).on('keydown','.main', function (e) {
oldValue = $(this).val();
});
var newValue;
$(document).on('keyup', '.main',function (e) {
newValue = $(this).val();
foo(oldValue,newValue);
});
function foo(orig){
$('#table2').find('tbody tr').each(function (i) {
var $td2 = $(this).find('td input:text');
if (orig == $td2.val()) {
$td2.val(newValue);
}
});
}
This is what happens,if I change "Apple" on table 1 slowly typing, "Apple" input field changes, but If I type too fast, my code is not working.
What if you add some relation between the original input-field and the corresponding like:
<input type='text' class= 'main' value="Apple" rel="sec_apple"/>
and
<input type='text' value="Apple" class="sec_apple"/>
for the second input.
Then you javascript could look like this:
$(document).on('keyup', '.main',function (e) {
foo($(this));
});
function foo(orig){
rel = orig.attr('rel');
var sec = $('.' + rel);
sec.val(orig.val());
}
Demo
Use JavaScript rather than jQuery. jQuery has a lot of overhead and can be too slow.
Probably not the case here. You do need to explain the issue a little better.
I ran a test and could not miss a key stroke, with my code.
My test routine changes the color of the background on each onkeyup.
I only used the two text inputs in table 1 to the right of Apple and banana.
Because I do not understand what you are doing, my test routine changes the color of the background on each onkeyup. If I type in 123456789 as fast as possible in both text fields they both come end with the correct color.
You may notice that I declare the inputs globally and use arrays instead of if else. Things that cannot be done efficiently with jQuery.
The reason I abandoned jQuery is I found jQuery to be way too slow on an iPad.
The following is tested at: This test Location
<!DOCTYPE HTML>
<html lang="en"><head><title>keys</title></head><body>
Table1
<form id='form1'>
<table id='table1'><tbody>
<tr><td><input type='text' class= 'main' value="Apple"/></td>
<td><input id="t1" type='text' class= 'main' value="" onkeyup="key(1)"/></td>
</tr><tr>
<td><input type='text' class= 'main' value="Banana" /></td><td><input id="t2" type='text' value="" onkeyup="key(2)"/></td>
</tr></tbody></table>
Table2
<table id='table2'><tbody>
<tr><td><input type='text' value="Apple" /></td></tr>
<tr><td><input type='text' value="Banana" /></td></tr>
<tr><td><input type='text' value="Banana" /></td></tr>
</tbody></table>
<br />
</form>
<script type="text/javascript">
//<![CDATA[
var color = new Array;
color[0] = '#f00';
color[1] = '#f0f';
color[2] = '#ff0';
color[3] = '#0ff';
var nc=[0,0,0];
var next = [1,2,3,0];
var txt=new Array;
txt[1] = document.getElementById('t1');
txt[2] = document.getElementById('t2');
function key(id){
nc[id] = next[nc[id]];
txt[id].style.background=color[nc[id]];
}
//]]></script></body></html>

Jquery selecting inputs with adjacent asterisk

Using jquery, I'm trying to select those inputs that have an asterisk adjacent to them.
HTML
<form name="checkout">
<table width="100%" border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="FirstName" value="" />*</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="LastName" value="" /></td>
</tr>
</table>
</form>
Jquery
var elems = $("form[name='checkout'] :input").filter(function(index) {
var str = $(this).parents('td').html()
return (str.indexOf("*")!=-1)
}).length;
Result of elems should be 1 but it's not working, i.e. the form submits in spite of a return false in the handler so can't seem to catch the error details. What am I doing wrong?
var elems = $("td:contains('*') input");
This is selector for the input elements that you need.
elems.length will give you 1 in this case
Ha Ha,
Missing the onReady().
Use this one,
$(function(){
var elems = $("form[name='checkout'] :input").filter(function(index) {
var str = $(this).parents('td').html()
return (str.indexOf("*")!=-1)
}).length;
console.log(elems);
});
That should do. Cheers :).
I suggest you to use CSS :after pseudo element
<style>
.mandatory:after{
content:"*";
}
</style>
<span class="mandatroy">
<input type="text" name="FirstName" value="">
</span>
<script>
$("form[name='checkout'] .mandatory > :input")
</script>
It would be easier, if you added a class to the inputs which have an asterisk after them:
<td><input type="text" name="FirstName" class="required" />*</td>
Then you could select them by their class and do whatever you wish to them.
$("input.required").length();
Given the explicit requirement:
$('input').filter(function () {
return (this.nextSibling && this.nextSibling.nodeValue.indexOf('*') > -1) || (this.previousSibling && this.previousSibling.nodeValue.indexOf('*') > -1);
}).css('border-color','#f00');
JS Fiddle demo.

Get Html Attributes inside div

<div>
<table>
<tr>
<td>
<input type="text" id="one" value="1" name="textbox"/>
</td>
<td>
<input type="hidden" id="two" value="2" name="hidden"/>
</td>
</tr>
<tr>
<td>
<input type="radio" name="group2" value="Water"> Water<br>
<input type="radio" name="group2" value="Beer"> Beer<br>
</td>
<td>
<span id="sdf" title="sdf">ok</span>
</td>
</tr>
</table>
<div>
Get Html Attributes inside div,How to get attribute like type,name,value
from above div using dom(traversing) for each elements like input,span etc
a simple search on google returned this guide for javascript. here you can find everything you need
I assume you're asking how to do this with javascript. Here's sample code for the objects with id values. For the other values, put id names on them too and use the same technique.
var input_one = document.getElementById("one");
var input_two = document.getElementById("two");
alert("Input one: type='" + input_one.type + "', name='" + input_one.name + "', value='" + input_one.value + "'");
And a fiddle that shows it in action: http://jsfiddle.net/jfriend00/nZyjN/
using getAttribute( "type" ) we can get value of the particular attribute
The querySelectorAll(selectors) method allows you, for a given element, to retrieve an array of its descendant elements that match given criteria.
For example:
// Replace "yourDiv" with a reference to you main div
var elements = yourDiv.querySelectorAll("input, span");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var name = element.name;
var type = element.type;
var value = element.value;
// Now you can do what you want with name, type and value, for example:
alert("Name: "+name+"\r\n"+"Type: "+type+"\r\n"+"Value: "+value);
}
According to the Mozilla Developer Network the querySelectorAll method is supported in IE8, Fx3.5, Chrome1, Opera 10 and Safari 3.2.

Categories