could not get input field value in jquery - javascript

I am creating an input field using foreach loop like this
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
$data is Array
(
[0] => Array
(
[asset_id] => abc-02
[asset_name] => Freezer
)
[1] => Array
(
[asset_id] => xyz-01
[asset_name] => Refrigerator
)
[2] => Array
(
[asset_id] => 300001
[asset_name] => Generator
)
)
and in javascript, I am trying to get the value using this code but it always alerts first value of the input.
<script type="text/javascript">
$(document).ready(function () {
var typename = $('#typename').val();
alert(typename);
});
</script>
i have to disable this input field when value is 'Generator'

Try:
$('[readonly].form-control').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="5">
</td>
.val() called once will always produce only one value; .val() docs:
Get the current value of the first element in the set of matched elements .
HTML id attribute is supposed to be unique, try this instead.
<?php
$count = 0;
foreach($data as $key=>$val) {
?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_<?php echo $count++; ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
It'll produce different id attributes for each input, typename_0, typename_1, ..., typename_n, allowing you to for example:
$('[id^="typename_"]').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_0" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename_1" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename_2" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename_3" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename_4" type="text" value="5">
</td>
Where [id^="typename_"] is CSS attribute selector, matching all elements with an id attribute starting with typename_.

You should never use same id for several elements.
Update you code for debug, and you'll see that you have an array:
<script type="text/javascript">
$(document).ready(function () {
var typename = $('[name="model[]"]')
.toArray().map(e => e.value);
alert(JSON.stringify(typename));
});
</script>
You should update your php, to set different id for each element drawn in a cycle, i.e:
<?php $i=1;foreach($nomatter as $a) {?>
<input id="typename_<?=$i++?>">
<?php } ?>
So you'll be able to address eash input separately:
var typename = $('#typename_1').val();

Use class instead of duplicate id like this.
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control clsValue" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery loop your class and get value using this instant..
$(document).ready(function () {
$( ".clsValue" ).each(function( index ) {
var typename = $(this).val();
alert(typename);
});
});

try this ,
this will call alert function for each input with form-control class
$(document).ready(function () {
$(".form-control").each(function(){
alert($(this).val());
})
});

Set class="typename" instead of id="typename":
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" class="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
You can get values like this:
<script type="text/javascript">
$(document).ready(function () {
var typename1 = $('.typename')[0].val();
var typename2 = $('.typename')[1].val();
alert(typename1);
});
</script>

there is a big mistake in your code, you can't use same id for multiple input fields, when the loop run multiple input fields will create with same id, you have to make the id dynamic, you can make the id dynamic by appending some unique value to the id each time you create an input field the use that id to fetch the data.
Please let me know if you need sample code.

pure js approach;
replace id with class;
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control typename" name="model[]" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
js
window.onload = alertTypeNames();
function alertTypeNames() {
document.getElementsByClassName('typename').map((inputTag) => {
alert(inputTag.value);
return true;
});
}

you fired with your id that's why it's fired only first element value.
this is how you can do that with your current code
$(document).ready(function () {
$('input[name="model[]"]').each(function(){
alert($(this).val());
});
});
However, it's highly recommended that you have to used unique id for each element otherwise used class to do what you want to.

The id attribute specifies a unique id for an HTML element it's not a good practice to use same ID more than once on a page, instead of ID attribute loop the class attribute in jquery.
<script type="text/javascript">
$(document).ready(function () {
$('.common-class').each(function() {
alert($(this).val());
});
});
</script>
<?php $incr_var = 1; ?>
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control common-class" name="model[]" id="typename<?php echo $incr_var ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>

Element id should be unique. And try it inside on event because dynamically adding elements will not grab ready state.
http://api.jquery.com/live/

<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1 status">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery
$(document).on('change','.status',function(){
var $status = $(this).val();
if($status == 'not_working'){
$(this).closest('tr').find('.reason').removeAttr('disabled');
}
});
reason is class you have to give which input field you want to disable

Related

Only last value from JavaScript in while loop is displayed

I'm working on the code displaying in the while loop data received from the database. Within that code there is a form in which I added a hidden input (name="position"). I'd like to use that input to store number of pixels from the top of the window. Unfortunately, the javascript added by me, changes the value of the hidden input only in the last table in the loop. In the first tables the hidden input named "position" remains unchanged (remains empty). Could anyone please help me?
<?php
while ($row = $wynik->fetch_assoc()) {
?>
<form method="post" style="margin-bottom: 0px;" onsubmit="poz()">
<input type="hidden" name="edition" value="<?php echo $row["id"]; ?>">
<input type="hidden" id="<?php echo $row["id"]; ?>" name="position" value="">
<input type="submit" value="Edytuj" class="edytuj">
</form>
<script>
function poz() {
var position = window.pageYOffset;
document.getElementById(<?php echo $row["id"]; ?>).value = position;
}
</script>
You need to add an event listener to know what is clicked
window.addEventListener("load",function() {
[...document.querySelectorAll(".edytuj")].forEach(function(elem) {
elem.addEventListener("click",function (e) {
var tgt = e.target;
tgt.previousElementSibling.value=tgt.offsetTop;
})
});
})
<input type="hidden" name="edition" value="<?php echo $row["id"]; ?>">
<input type="hidden" id="<?php echo $row["id"]; ?>" name="position" value="">
<input type="button" value="Edytuj" class="edytuj">

Get the values of while loop using button with js

How can I get the values in the while loop using button with js?
<?php
while ($row = mysqli_fetch_array($query))
{
echo '<input type="text" name="sample" value="'.$row['sample'].'">';
}
?>
Thanks
You can get the value of textbox when you click on a button.
<input type="text" name="sample[]" value="abc" class="valueInput">
<input type="text" name="sample[]" value="xyz" class="valueInput">
<input type="text" name="sample[]" value="pqr" class="valueInput">
<input type="button" class="getValue" value="Get Value">
Note: I have set the static input box you can make it dynamic but make sure please add the class as valueInput.
Jquery Code.
$(document).on('click','.getValue',function(){
var valArr = [];
$(".valueInput").each(function(){
valArr.push($(this).val());
});
console.log(valArr);
})
The name of the input field should indicate an array with [].
<form action="action.php" method="POST">
<?php
while ($row = mysqli_fetch_array($query)){
echo '<input type="text" name="sample[]" value="'.$row['sample'].'">';
}
?><input type="submit">
</form>
action.php: (Processes the data on submit)
<?php
echo "<pre>";
print_r($_POST['sample']);
echo "</pre>";

accessing id as array in ajax(php)

friends.I am stuck with some javascript function to read keyup function to a text field with id as array(qty[]).Please help me
<table id="dynamic">
<tr>
<td>
<label for="textfield">product :</label>
</td><td> <select name="product" id="product[0]">
<?php
$result=mysql_query("SELECT * FROM `product`");
while($row=mysql_fetch_array($result)){
?>
<option value=" <?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php }?>
</select>
<label for="qty">Qty :</label>
<input type="text" name="qty" id="qty[0]"/>
<label for="textfield">Price :</label>
<input type="text" name="price" id="price[0]" readonly/>
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
</td> <div id="loader"></div></tr>
</table>
javascript
appending dynamic fields
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
$('#dynamic').append('<tr id="row'+i+'"><td><label for="textfield">product :</label></td><td><select name="product" id="product['+i+']"><?php $result=mysql_query("SELECT * FROM `product`");while($row=mysql_fetch_array($result)){?><option value=" <?php echo $row['id']; ?>"><?php echo $row['name']; ?></option><?php }?></select><label for="qty">Qty :</label><input type="text" name="qty" id="qty['+i+']"/><label for="textfield">Price :</label><input type="text" name="price" id="price['+i+']" readonly/></td><td><button type="button" name="remove" class="btn btn-danger btn_remove" id="'+i+'">X</button></td></td><div id="loader"></div></tr>');
i++;
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
here i tried to access the qty[0] variable.but its not working.When its not array working fine.
<script type="text/javascript">
$(document).ready(function()
{
var i=1;
$("#qty[0]").keyup(function()
{
var qty=$("#qty[0]").val();
var pdt=$("#product[0]").val();
i++;
$.ajax({
type:"POST",
url:"price_ajax.php",
data : { qty : qty, pdt : pdt },
beforeSend: function () {
$('#loader').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success:function(data)
{
$("#price[0]").val(data);
$("#loader").html("");
}
});
});
});
Change
$('#add').click(function() {
$('#dynamic').append('... id="product['+i+']">...');
i++;
});
To
$('#add').click(function() {
$('#dynamic').append('... id="product_'+i+'">...');
i++;
});
id="product[0]" will become id="product_0"
Apply same method to other dynamic elements and make relevant modifications in your jQuery selector.
Everything will work fine.
Also, I would like to add here that, please break up your append call. Javascript, HTML and PHP, everything is happening in one single line. Which is very confusing. Prepare an HTML in javascript variable. Once done, append it.
Update your code as mentioned below:
HTML Changes:
Add class class='qty' in input box in id="qty[0]" field
$('#add').click(function(){
$('#dynamic').append('<tr id="row'+i+'"><td><label for="textfield">product :</label></td><td><select name="product" id="product['+i+']"><?php $result=mysql_query("SELECT * FROM `product`");while($row=mysql_fetch_array($result)){?><option value=" <?php echo $row['id']; ?>"><?php echo $row['name']; ?></option><?php }?></select><label for="qty">Qty :</label><input type="text" name="qty" class="qty" id="qty['+i+']"/><label for="textfield">Price :</label><input type="text" name="price" id="price['+i+']" readonly/></td><td><button type="button" name="remove" class="btn btn-danger btn_remove" id="'+i+'">X</button></td></td><div id="loader"></div></tr>');
i++;
$( ".qty" ).each(function( index ) {
$(this).keyup(function() {
// your code here
});
});
});
Jquery Changes:
$( ".qty" ).each(function( index ) {
$(this).keyup(function() {
// your code here
});
});

Cant read value from field jquery mobile

my html code
<?php
while($results = $user_class->fetch_array($sql)){
?>
<input type="text" name="price[]" class="price" id="price"
size="5px" readonly value="<?php echo $results['price_v'] ?>">
<select onChange="update(); return false;" name="qty[]" class="quant">
<option value="0"></option>
<?php
$limit = $results['limiter'];
for($i=1;$i <= $limit;$i++ ){
?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php } ?>
</select>
this is my jquery code
$("#example_form tr.raww").each(function(i,o){
if($(o).find(".quant").val()>0) {
total += $(o).find(".quant").val() * $(o).find(".price").val();
}
});
if i attach
<script type="text/javascript" src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
My jQuery can't read the value from the field.
And if i remove that jquery mobile can read value from field.
http://jsfiddle.net/QJxYv/3/
Is there anything wrong with my jQuery code?
Your code will work as long as there is only one element with class quant and one element with class price in each row of class raww.
Try the following:
if ($(this).find("select.quant").val() > 0) {
and
sub_total += $(this).find("select.quant").val() * $(this).find(".price").val();
Updated fiddle:
http://jsfiddle.net/QJxYv/4/

jquery regex out 0 from cloned element and insert it?

I'd like to learn how to regex out 0 from all elements inside clone and replace it with var count_rows.
//Duplicate table tr for multiple subtitle entry
$("#add_subtitle").on("click", function(){
var count_rows = $(".subs_row").length;
$("#sub_0").clone().insertBefore("#append_sub");
return false;
});
markup:
<tr valign="top" id="sub_0" data-num="0" class="subs_row">
<th scope="row"><label for="subtitle">Subtitle_0</label></th>
<td>
<input name="subtitle[0][url]" type="text" value="<?php echo $wovies_extra_data[0]['subtitle'][0]['url']; ?>" style="width:280px;">
<p class="howto">Url</p>
</td>
<td>
<input name="subtitle[0][lang]" type="text" value="<?php echo $wovies_extra_data[0]['subtitle'][0]['lang']; ?>" style="width:100px;">
<p class="howto">Language: Label</p>
</td>
<td>
<input name="subtitle[0][lang_code]" type="text" value="<?php echo $wovies_extra_data[0]['subtitle'][0]['lang_code']; ?>" style="width:50px;">
<p class="howto">Language: Code</p>
</td>
<td>
<input name="subtitle_def" type="radio" value="<?php echo $key; ?>" <?php if ($wovies_extra_data[0]['subtitle_def'] == $key) {echo "checked";} ?> style="width:100px;">
<p class="howto">Default?</p>
</td>
</tr>
oh and how can I make my regex not touch zero in width:50px; ?
Regexp is probably the wrong way to go here.
I would suggest to use a template system like http://mustache.github.io/ or underscore
If you really want to replace the zeros inside your existing HTML code you could target only certain attributes:
function replaceZero(row) {
return function (i, value) {
return value.toString().replace(0, row);
}
}
var $row = $("#sub_0");
$("label", $row).text(replaceZero(200));
$("input", $row).attr("name", replaceZero(200));
$row.attr("id", replaceZero(200));
Fiddle (simplified)
Fiddle (with clone)

Categories