I have this element in the DOM, which I can read by using this:
e.target.parentElement.parentElement.childNodes[1]
It renders as this (in the console):
e.target.parentElement.parentElement.childNodes[1]
<td>
"
1
"
<input length="9" data-val="true" data-val-number="The field TarriffID must be a number." data-val-required="The TarriffID field is required." id="TarriffID" name="TarriffID" type="hidden" value="44">
</td>
This is the Markup for it:
<tbody id="TarriffsGrid">
#if (Model.ContractTarriffsList.Count != 0)
{
foreach (var tarriff in Model.ContractTarriffsList)
{
var count = 1;
<tr>
<td>
#(count.ToString(CultureInfo.InvariantCulture))
#Html.Hidden("TarriffID", tarriff.TarriffID.ToString(CultureInfo.InvariantCulture), "TarriffID")
</td>
<td>
#(Math.Round(tarriff.ExcessValue, 2))
</td>
<td>
#(Math.Round(tarriff.Rate, 2))
</td>
<td>
<input type="radio" name="radioInput" id="radioInput" class="tarriffRadioButton" />
</td>
</tr>
count++;
}
}
</tbody>
I would like to get the value of (44), but this is not happening with any of the following variations:
e.target.parentElement.parentElement.childNodes[1].val();
e.target.parentElement.parentElement.childNodes[1].val;
e.target.parentElement.parentElement.childNodes[1].value;
e.target.parentElement.parentElement.childNodes[1].value();
e.target.parentElement.parentElement.childNodes[1].text;
e.target.parentElement.parentElement.childNodes[1].innerText;
...etc.
What could possibly be the solution here please?
Solved with this:
var tarriffID = e.target.parentElement.parentElement.childNodes[1].firstChild.value;
Many thanks.
Edit
It was actually this (one step deeper):
e.target.parentElement.parentElement.childNodes[1].childNodes[1].value;
Related
How can I iterate over the following HTML using Javascript in order to add a 1 to all the name fields. For example, "account" would become "account1", etc. I cloned this row from a table, and would like to be able to distinguish between the fields of the two.
<td>
<select name="account">…</select>
</td>
<td>
<span>
"$ "<input type="text" name="debit" placeholder="100">
</span>
</td>
<td>
<span>
"$ "<input type="text" name="credit" placeholder="100">
</span>
</td>
<td>
<input type="text" name="reference">
</td>
<td>
<input type="text" name="notes">
</td>
<td>
<select name="account">...</select>
</td>
One way you can do this is use querySelectorAll to get your elements inside your table, then use a loop and change their names:
var inputs = document.querySelectorAll("#myTable [name]")
inputs.forEach(function(input){
input.name += + "1";
});
JSFiddle Demo
var all =document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++){
if(all[i].name){
all[i].name+=1;
}
}
Try this.* will give you all elements in the page.
my table looks like this.
<body>
<table class="tblTest">
<tr>
<td>
<label>wer</label></td>
<td>
<label>ur4</label></td>
<td>
<label>ksdj</label></td>
</tr>
<tr>
<td>
<label>eiejr</label></td>
<td>
<label>ur4</label></td>
<td>
<label>yutu56</label></td>
</tr>
<tr>
<td>
<input type="text" /></td>
<td>
<input type="text" /></td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<label>jweee</label>
</td>
<td>
<label>male</label>
</td>
<td>
<label>ur4</label>
</td>
</tr>
<tr>
<td>
<label>ssssss</label>
</td>
<td>
<label>male</label>
</td>
<td>
<label>ur4s</label></td>
</tr>
<tr>
<td>
<input type="text" /></td>
<td>
<input type="radio" name="gender" value="male" />Male
<br />
<input type="radio" name="gender" value="female" />Female
</td>
<td>
<select name="cars" style="width: 128px">
<option selected="selected" value="Select">Select</option>
<option value="saab">BMW</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</td>
</tr>
</table> <br />
<button type="button" onclick="function1()">Submit</button>
I want a Java script/jQuery which will check the two labels and if there is a mismatch then it will make the Text Box Red and if not then green. I can't use getElementById for the labels only I have to traverse through it and get the td index and do the task. I Don't know how to get prev and closest elements. Please help me with this.
The function which I'm trying is
function function1() {
var inputcontrols = document.getElementsByTagName('input');
for (var i = 0; i < inputcontrols.length; ++i)
{
var element = inputcontrols[i];
//element.style.background = "#90EE90"; by default making it green
var ind = $(this).closest('td').prev('td').text();
alert(ind);
}
Trying to get the td text in "ind", but its returning empty.
First get all the inputs, and use the each loop to iterate these. And by using the index to get the appropriate label texts.
The reason text() did not work for you, is because you are trying to get the text from the td element. This is empty, because it only contains a HTMLElement label. Look at the jQuery specs to see the difference between text() and html()
function function1() {
$('table').each(function(n, table) {
$(table).find('tr').each(function(n, tr) {
tr = $(tr);
var td = undefined;
var c = 0;
tr.find('input,select').each(function(i, input) {
if(!td || !td.is($(input).closest('td'))) {
td = $(input).closest('td');
c++;
}
var lbl1 = $(tr.prev().prev().find('td')[c]).find('label').text();
var lbl2 = $(tr.prev().find('td')[c]).find('label').text();
if(lbl1 === lbl2) {
$(input).css('backgroundColor', 'green');
} else {
$(input).css('backgroundColor', 'red');
}
});
});
});
}
The first problem I see is that you're using $(this) which is what how you chain the function scope in jQuery. For example:
$('a').each(function() {
// 'this' scopes to the current 'a' element inside the 'each' loop
$(this).css('color', '#FF0000');
});
Since you've already found your input controls and stored them in var element you need to pass that element into jQuery so it knows what you're looking for.
var element = inputcontrols[i];
$(element).closest('td').prev('td').text();
Next, if you're trying to compare the text field to the previous label you need to fix your traversal steps to be:
From the text field
Find its parent tr not td (go up to the row)
Find its the previous tr (go back a row)
Find its child label (drill down into the previous row)
Get the text from the label
assuming that you only have two table rows, you can try this-
function function1() {
var inputs = $('.tblTest input');
var tr1 = $('.tblTest tr:nth(0)');
var tr2 = $('.tblTest tr:nth(1)');
for (var i = 0; i < inputs.length; ++i)
{
var element = inputcontrols[i];
if(tr1.find('td:nth('+ i +') label').html().trim() == tr2.find('td:nth('+ i +') label').html().trim()) {
element.style.background = "green";
}
else {
element.style.background = "red";
}
}
}
I have a list of textboxes as follows :
` <table id="div1" style="width:100%;">
<tr>
<td>
<label>Question Text</label>
</td>
<td colspan="5">
<textarea rows="4" cols="500" name="questiontext" id="questiontext" > <?php print $view->questions->getQuestion_Text() ?></textarea>
</td>
</tr>
<tr>
<td> <label>Option a) </label></td>
<td colspan="5"> <textarea rows="1" cols="200" name="Optiontext[]" id="text1"> </textarea> </td>
</tr>
<tr>
<td> <label> Option b) </label></td>
<td colspan="5"> <textarea rows="1" cols="200" name="Optiontext[]" id="text2"> </textarea> </td>
</tr>
<tr>
<td>
</td>
</tr>
</table>`
I need to pass the values to a jquery function as follows :
$(document).ready(function(){
$('#question').live('submit',function(){
var params={};
params.action='saveQuestion';
params.questionid=$('#questionid').val();
params.questiontext=$('#questiontext').val();
return false;
})
});
My question is how do i pass the values of the textarea to the jquery function as textarea can be dynamically created.
I tried to access the values of textarea directly in php as follows but the values are not passed:
$option_key = 1;
for($i = 0;$i<= count($_POST['Optiontext']);$i++){
$option = $_POST['Optiontext'][$i];
if(isset($option))
{
$query_options="INSERT INTO `XXX`(`Question_ID`, `Option_Key`, `Option_Value`) VALUES ($max_id,'$option_key','$option')";
$sql = mysql_query($query_options)or die($query_options."<br/><br/>".mysql_error());
$option_key = $option_key + 1;
}
}// for loop ends
The contents of each textarea are posted to the form as a comma-delimited variable called 'Optiontext[]'.
Since commas can be added in the textareas, it could get interesting trying to split the data back into the correct fields! Possibly a better solution would be a finite number of textarea fields with unique names, or dynamically create them as needed using javascript/jQuery.
I was able to pass the value of textboxes by map function as follows
$(document).ready(function(){
$('#question').live('submit',function(){
var params={};
params.action='saveQuestion';
params.questionid=$('#questionid').val();
params.questiontext=$('#questiontext').val();
var Optiontext = [];
Optiontext = $('textarea[name^="Optiontext\\["]').map(function() {
var value_textarea = $(this).val();
if(value_textarea && value_textarea != ' ')
{
return $(this).val();
}
}).get();
params.Optiontext=Optiontext;
return false;
}) });
Well I've ripped my hair off because I assumed I was finished this script but suddenly adding ONE more for loop broke every single indexOf, I tried to create checks so the console wouldn't freak out, but sadly no success. using a static value for "z" or LevelCheck allows for all the indexOfs to work properly but as soon as a for loop is involved, it seems none of the indexOfs wishes to work
<script type="text/javascript">
var tempval = new Array();
function Renew(){ //Reset tempval back to val
for(d=0;d<val.length;d++){
tempval[d] = val[d];
}
}
function UpdateLoop(){
Renew();
var Levels = document.getElementById("Lvl");
if(Levels){
for(z=0; z<=Levels.value; z++){
Update(z);
}
}
}
function Update(LevelCheck){
for (i=0; i<=key.length; i++){
if(key[i] != null){
if ( key[i].indexOf("rate") > -1 ) { //Search through
for (r=0; r<=key.length; r++){
if(key[i].indexOf(key[r]) > -1){ //Finds out which form it should replace
var raw=tempval[i];
for (y=0; y<=key.length; y++){
if(key[i] != "movespeed" && key[i] != "Movrate"){ //add a check to see if string is not there
var item = document.getElementById(key[y]);
if (item) { //Make it use formula value and then put that result into a value and loop back into function until level reached. If level changed to a lower number, reset to original value and repeat
//raw=raw.replace(key[y],document.getElementById(key[y]).value); //replace this with val[y]
raw=raw.replace(key[y],tempval[y]);
}
}
else
break;
}
if(raw != null){
if(raw.indexOf("Mov") > -1){
for(x=0; x<=key.length; x++){
if(key[x].indexOf("movespeed") > -1){
//raw=raw.replace("Mov",document.getElementById(key[x]).value);
raw=raw.replace("Mov",tempval[x]);
break;
}
}
}
if(raw.indexOf("Lvl") > -1){
raw=raw.replace("Lvl",document.getElementById('Lvl').value);
}
if(raw.indexOf("Exp") > -1){
raw=raw.replace("Exp","0");
}
}
if( document.getElementById('Lvl').value == LevelCheck){
alert("Input:"+tempval[i]);
if(key[i] == "Movrate"){
document.getElementById("movespeed").value = eval(raw);
}
else{
var check = document.getElementById(key[r]);
if (check){
document.getElementById(key[r]).value = eval(raw);
}
}
}
else{
tempval[r] = eval(raw);
}
break; //So it doesn't keep searching
}
}
}
}
}
}
</script>
Html portion(This is generated via php so I just used what the browser generated)
<table>
<tbody>
<tr>
<td>Creature Name:</td>
<td>
<input type="Text" name="CName" value="Thing" size="10%">
</td>
</tr>
<tr>
<td>Level:</td>
<td>
<input type="Text" id="Lvl" name="level" onchange="" value="1" size="10%">
</td>
</tr>
<tr>
<td>movespeed:</td>
<td>
<input type="Text" name="movespeed" id="movespeed" value="1" size="10%">
</td>
</tr>
<tr>
<td>str:</td>
<td>
<input type="Text" name="str" id="str" value="4" size="10%">
</td>
</tr>
<tr>
<td>dex:</td>
<td>
<input type="Text" name="dex" id="dex" value="3" size="10%">
</td>
</tr>
<tr>
<td>int:</td>
<td>
<input type="Text" name="int" id="int" value="1" size="10%">
</td>
</tr>
<tr>
<td>will:</td>
<td>
<input type="Text" name="will" id="will" value="2" size="10%">
</td>
</tr>
<script type="text/javascript">
var key=new Array();
var val=new Array();
key.push("movespeed");
val.push("1");
key.push("str");
val.push("4");
key.push("dex");
val.push("3");
key.push("int");
val.push("1");
key.push("will");
val.push("2");
key.push("Movrate");
val.push("Mov+1");
key.push("strrate");
val.push("1+str");
key.push("dexrate");
val.push("1+dex+(str/4)");
key.push("intrate");
val.push("1+int");
key.push("willrate");
val.push("1+will");
</script>
<tr>
<td>
<input type="button" name="button" value="Use Formula" onclick="UpdateLoop();">
</td>
<td>
<input type="submit" value="Save">
</td>
Console:
Uncaught TypeError: Object 2 has no method 'indexOf' Monsters.php:62
Update Monsters.php:62
UpdateLoop Monsters.php:39
onclick Monsters.php:28
you need to change your Update function to the following:
function UpdateLoop(){
var Levels = document.getElementById("Lvl");
if(Levels){
for(z=0; z<=Levels.value; z++){
Renew();
Update(z);
}
}
}
After processing Level 0, the tempval array had the values from Level 0, which wiped out the original values from the val array.
Making this change fixed the problem in my tests: http://jsfiddle.net/jimmym715/xTUND/
oh, and what MaxArt said in the comments above is right on the money... there are far better ways to accomplish what you're going for here
Turns out that flat numbers are NOT strings so in order to safely go through every value .toString() had to be present, thanks everyone for trying though.
so it would look like:
key[i].toString().indexOf(key[r])
I need to create sum of the values selected, but i have small problem with the jquery bit.
My html table
<TR>
<TD>
<INPUT disabled onchange=updateDetails() value=33441 CHECKED type=checkbox name=invoiceRow dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees for Searches</TD>
<TD>285.00</TD></TR>
<TR>
<TD><INPUT onchange=updateDetails() value=36486 CHECKED type=checkbox name=invoiceRow dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees</TD>
<TD>3213.03</TD></TR>
my javascript is:
where #InvoiceItemsRows is <tbody> tag
function updateDetails() {
$("#InvoiceItemsRows input[type=checkbox][checked]").parent().last().each(
function(index, value) {
alert(value.html());
}
);
}
Javascript, maybe not as fancy as some of the other ones people have posted but it makes sense.
$(document).ready(function() {
$('[name=invoiceRow]').click(function() {
updateDetails();
});
function updateDetails() {
var total = 0;
var currentnum = 0;
$("input:checked").each(
function(index, value) {
currentnum = $(this).val();
currentnum = Number(currentnum);
total = total + currentnum;
});
alert(total);
}
});
HTML
<TR>
<TD>
<INPUT disabled value="33441" CHECKED type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees for Searches</TD>
<TD>285.00</TD></TR>
<TR>
<TD><INPUT value="36486" CHECKED type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees</TD>
<TD>3213.03</TD></TR>
I fixed some of the missing quotes you may want to finish fixing them though.
Try this (you have to close <Input> tags):
function updateDetails() {
var sum = 0;
$("#InvoiceItemsRows input[type=checkbox]:checked").each(
function() {
sum += parseFloat($(this).closest('tr').children('td:eq(2)').text());
}
);
return sum;
}
alert(updateDetails());
You'll have to change:
$("#InvoiceItemsRows input[type=checkbox][checked]")
To:
$("#InvoiceItemsRows input:checked")
That new rule will return all 'checked' elements. Have a look at the documentation of the :checked selector.
Try this:
var total = 0;
$('#InvoiceItemsRows input:checked').each(function() {
total += $(this).val();
});
I suspect you want to total what's in the <td> though?
you have invalid html your your values need quotes
<tr>
<td>
<input disabled="disabled" onchange="updateDetails()" value="33441" checked="checked" type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"> <input type="hidden" name="isProfFee">
</td>
<td>
Professional fees for Searches
</td>
<td>
285.00
</td>
</tr>
<tr>
<td>
<input onchange="updateDetails()" value="36486" checked="checked" type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"> <input type="hidden" name="isProfFee">
</td>
<td>
Professional fees
</td>
<td>
3213.03
</td>
</tr>
and then
$("#InvoiceItemsRows input:checked")