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.
Related
I have the table with following structure . I am generating a dynamic table on the basis of input provided by user which will repeat this row .
I want to get the value of this text box and trying to use the code below
if (row.getAttribute('val') === 'answer') {
var Cell = table.rows[i].cells[0];
alert(Cell.innerHTML);
}
<tr val='answer'>
<td>
<input type='checkbox' />
<input style='width:483px' type='text' />
</td>
</tr>
I am putting alert to check if i am getting the correct value .I can see the two inputs in the alert message I want to get the value of text box using javascript not jquery
You can use querySelectorAll to select all rows and then use loop to get only rows with val='answer' and then use querySelector to get input with type="text"
var rows = document.querySelectorAll('tr');
for (var i = 0; i < rows.length; i++) {
if (rows[i].getAttribute('val') == 'answer') {
var input = rows[i].querySelector('input[type="text"]');
console.log(input.value);
}
}
<table>
<tr val='answer'>
<td>
<input type='checkbox' />
<input value="Some value" style='width:483px' type='text' />
</td>
</tr>
</table>
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;
}) });
I have following code
<tbody>
<tr>
<td style="width:40%">
<select id="pname.0" name="pname[]" class="form-control ">
<?php
$this->db->order_by('name','asc');
$prod = $this->db->get('product')->result_array();
foreach($prod as $row): ?>
<option data-price="<?php echo $row['price'];?>" value="<?php echo $row['prod_id'];?>" >
<?php echo ucwords($row['name']);?>
</option>
<?php endforeach; ?>
</select>
</td>
<td style="width:10%">
<input class="form-control" onchange="javascript:calc();" id="item_quantity.0" name="qnty[]" value=""/>
</td>
<td class="text-right" style="width:10%">
<input class="form-control text-right" onchange="javascript:calc();" id="item_price.0" name="price[]" value=""/>
</td>
<td class="text-right" style="width:10%">
<input class="form-control text-right" id="subtot.0" readonly name="item_sub_total" value=""/>
</td>
</tr>
</tbody>
Now I want to get the value of data-price attribute of selected option on change in Dropdown to the textbox having dynamic id item_price_0. This is changing as I have added the add row button. When I click on Add row, the id will become item_price_1.
Kindly help me how can I get these value using jquery or javascript
Is this what you were after?
//if your table has an id or class, use it as tag selector is not good without context.
//$(".tableClass") OR $("#tableID")
$("table").on('change', "select[id^='pname']", function() {
var $row = $(this).closest("tr");
$row.find("input[id^='item_price']").val( $(this).find('option:selected').data("price") );
});
So, to use . in selectors, you need to escape them as mentioned (2nd para) in jQuery selectors API
Demo#fiddle
You can listen the change on your element, and get the price attribute like so:
$('#pname.0').on('change', function(){
var price = $(this).find('option:selected').data('price');
});
PS: I'm not sure you can use "." in ID attribute.
First assign a class to all select. (in addition to "form-control"). I suppose selects have test class
var selectedPrices = [];
var i = 0;
$(".test").each(function(){
selectedPrices[i] = $(this).find(":selected").attr("data-price");
i++;
});
Now, selectedPrices is an array of prices. You can do anything you want with it.
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;