retrieve value of input - javascript

I have this:
<?php $i=0;?>
<?php foreach($x as $y): ?>
<input type="hidden" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>
<?php $i = $i + 1; ?>
<?php endforeach; ?>
I need to get the value of each "theid" like this:
<script type="text/javascript">
function somefunction(element, optionTitle) {
var num = document.getElementById('theid').value;
...
</script>
How can i do that considering the fact that "theid" has the $i added?
Thanks.

If you have multiple input fields and you want to do the same action on several, you could use getElementsByClassName instead of getElementById:
PHP
<input type="hidden" class="theclassname" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>
JS:
<script type="text/javascript">
function somefunction(element, optionTitle) {
var myEles = document.getElementsByClassName('theclassname');
// loop over myEles and act on each one
for (var i=0; i < myEles.length; i++) {
alert("Input with id: " + myEles[i].id + " has value: " + myEles[i].value);
}
}
</script>

I would recommend using jQuery, jQuery selectors support wildcards:
$('input[id^=theid]')
See http://api.jquery.com/category/selectors/ for further reading on this topic.

If you are using jQuery would be easy like this:
$('input[id^="theid"]').each(function () {
console.log($(this).val()); //value of each theid
});
Here is a jsBin.

Related

Retrieve The PHP variable Value of a HTMl Element Using Jquery inside a Loop

I have a strange problem. I am getting the table values using PHP MySQL using a while loop and stored them in a array. Then I am displaying it one after another in a single page.
$sql = "select * from newsfeed order by id DESC";
$result = $db->query($sql);
$posts_array = array(); // Storing the result to an Custom Array
$index = 0;
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$posts_array[$index] = $row;
$index++;
}
}
I have successfully set the $post_id of the posts on to the HTML elements using the following code.
<?php
$array_size = sizeof($posts_array);
for($i = 0; $i < $array_size; $i++){
?>
<div class='wrapper' id='wrapper'>
<div class='user'>
<!-- Some Code -->
<?php
$post_id = $posts_array[$i][id];
?>
<input type='image' name='like' id='like' width='40' height='40' src='like_btn.png' value='<?php echo ($post_id);'?> />
<?php } ?>
Now I want to take that value using Jquery and do some Database Work. I have accessed the value using the following code:
<script type="text/javascript">
function justsomething() {
alert($(this).val());
}
</script>
The problem is I am only getting the last post's id as alert() for every post rather than getting different id's .
Please help me. I am confused whether the PHP script is loading every time I click and call the justsomething() function.
Note: I can display the $post_id of every post alone without any problem.
Beacuse the id should be unique to one html element try changing your code to this :
<?php $array_size = sizeof($posts_array); for($i = 0; $i < $array_size; $i++){ ?>
<input type='image' name='like_<?php echo $i ?>' id='like_<?php echo $i ?>' width='40' height='40' src='like_btn.png' value='<?php echo $post_id;?>' onclick='justsomething(this);' />
<?php } ?>
<script>
function justsomething(el) {
var img = el;
alert(img.value);
}
</script>
here is an example
function justsomething(el) {
var img = el;
alert(img.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='image' name='like_1' id='like_1' width='40' height='40' src='like_btn.png' value='15454' onclick='justsomething(this);' />
It works for loop, I hope You can make use of it
$("input[id=like]").each(function(i){
alert($(this).val());
});
It will alert values from every <input id="like"...
Try this code:
onclick='justsomething(this)'
function justsomething(obj) {
alert($(obj).val());
}

Exploding string and putting values in <select>

I have a column in my db, tip_sting:
1 row example(each one has the same format):
G1-11, G2-21, P2-50, P4-20, P100-2,
I'm using this when editing a item(I want to create(as many selects in the string) and put the values automaticaly in the select) :
https://jsfiddle.net/avrzwt6k/
So I was thinking of doing something like:
$pieces = explode(",", $tip_stingu);
$a=count($pieces); // piece1
echo $a;
echo '<br>';
echo $pieces[1]; // piece2
echo '<br>';
$tip_stinga=explode("-",$pieces);
I just dont know how could I continue?
Do you need something like this?
<?php
$items = "G1-11, G2-21, P2-50, P4-20, P100-2";
$pieces = explode(",", $items);
echo ("<select>");
foreach ($pieces as $piece) {
$tip_stinga = explode("-", $piece);
echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
}
echo ("</select>");
?>
Using PHP & Javascript you can do:
<html>
<body>
<form id="example" name="example">
<select name="myName" id="myID" onchange="updateText()">
<?php
$tip_stingu = "G1-11, G2-21, P2-50, P4-20, P100-2,";
$pieces = explode(', ', $tip_sting);
$piece1 = explode('-', $pieces[0])[1];
foreach($pieces as $piece) {
$tip_stinga = explode("-", $piece);
echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');
}
echo '</select><input type="text" value="'.$piece1.'" id="quantity" /><br />'
?>
</form>
<script>
function updateText() {
document.getElementById("quantity").value = document.getElementById("myID").value;
}
</script>
</body>
</html>
You also have a trailing comma at the end of your example, if that's a problem you can use:
echo ('<option value="'.rtrim($tip_stinga[1], ',').'">'.$tip_stinga[0].'</option>');
instead of:
echo ('<option value="'.$tip_stinga[1].'">'.$tip_stinga[0].'</option>');

How to display a text after selecting an item name in the dropdown list, the text to be displayed is not the value of select

I wanted to display the description of an item after selecting the item name in the dropdown. I saved the values of the items with its corresponding description in an array using php. so this is my code in php (it is inside a loop):
$item_name[] = ucfirst($row['item_name']);
$desci[] = ucfirst($row['descr']);
Then I have this script (which is not working)
function updateText(val)
{
var $el = document.getElementById("adv1");
for($i=0; $i < <?php echo $ctr ?>; $i++)
{
if(val == '<?php echo "'.$itemid[$i].'" ?>')
{
$el.value = "$ 750";
}
else
{
$el.value = "0";
}
}
}
and here is my html code
<select name="item" id="datetime" onchange="updateText(this.value)" autofocus required>';
for ($i=0; $i < $ctr; $i++) {
echo ' <option value="'.$itemid[$i].'">'.$item_name[$i].' '.$brand[$i].' </option>';
}
echo '</select><p id="adv1"> </p>';
I was wondering how to retrieve the data from php and use it in javascript. Sorry, newbie here. Any help is appreciated, TIA!
<?php
echo '<select name="item" id="datetime" onchange="updateText(this.options[this.selectedIndex].getAttribute(\'data-val\'))" autofocus required>';
for ($i=0; $i <$ctr; $i++) {
echo ' <option value="'.$itemid[$i].'" data-val="'.$desci[$i].'">'.$item_name[$i].' '.$brand[$i].' </option>';
}
echo '</select><p id="adv1"> </p>';
?>
<script>
function updateText(nttest){
document.getElementById("adv1").innerHTML=nttest;
}
</script>
hope it will help, In data-val you can pass value what you need to display in adv1
You need to use ajax , ajax is simple to use , just follow the example on this link , it just refreshes the div so you don't have to refresh the entire page just to display something
http://www.w3schools.com/ajax/

Replacing Value of Input based off of the sun of two inputs

Im trying to add up the sum of two inputs that already have a value in it. I wanted the sum to change value if any of the other two inputs change in value. I have this the following, but its not working:
<?php
while($row = mysqli_fetch_array($test)) {
echo "<tr class='saved_add'>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><select'>";
echo "<option value='service'";
if ($row['type'] == "service") {
echo "selected='selected'";}
echo ">Service</option>";
echo "<option value='hours'";
if ($row['type'] == "hours") {
echo "selected='selected'";}
echo ">Hours</option>";
echo "<option value='days'";
if ($row['type'] == "days") {
echo "selected='selected'";}
echo ">Days</option>";
echo "<option value='product'";
if ($row['type'] == "product") {
echo "selected='selected'";}
echo ">Product</option></select></td>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><input class='subtotal'/></td>";
echo "</tr>";
}
mysqli_close($con);
?>
JQuery:
$('.saved_add').each(function() {
sum = $('input:eq(2)', this).val() * $('input:eq(5)', this).val();
$(".subtotal").text(sum);
});
any ideas?
Something along these lines:
function calculateSum() {
$('.saved_add').each(function() {
sum = $('input:eq(2)', this).val() * $('input:eq(5)', this).val();
$(".subtotal").text(sum);
});
}
// On first load
calculateSum();
// On change
$("input").change(calculateSum);
Your code will only calculate the value WHEN IT LOADS. You want to calculate it when it loads AND when the value changes, so you need the .change() function.
When you call .val() on an element it returns its value as a string. You have to convert it to a number first before you can do mathematical operations with it. To convert strings to integers, you can use the parseInt() method.
$('.saved_add').each(function() {
var sum = $('input:eq(2)', this).val() * $('input:eq(5)', this).val();
$(".subtotal").text(sum);
});
Edit, updated
Try
$('.saved_add').each(function(i, el) {
$(el).on("change", function() {
// cast `sum` as `Number`
sum = Number($('input:eq(2)', this).val() * $('input:eq(5)', this).val());
$(".subtotal").text(sum);
}).change();
});
jsfiddle http://jsfiddle.net/guest271314/20jeoc9y/
Thanks everyone for helping, i figured it out. Helps out to make each input as an ID so you can change it accordingly.
HTML:
<div id="saved1">
<input type="text" value="10" /><input type="text" value="10" /> <input type="text" value="10" />
<div id="subtotal1"></div>
</div>
<div id="saved2">
<input type="text" value="10" /><input type="text" value="10" /> <input type="text" value="10" />
<div id="subtotal2"></div>
</div>
JQuery:
function calculateSum() {
$("[id^=saved]").each(function() {
sum = $('input:eq(0)', this).val() * $('input:eq(1)', this).val();
$('input:eq(2)', this).val(sum);
});
}
// On first load
calculateSum();
// On change
$("input").change(calculateSum);
JSFiddle

How to get jquery value from for loop in php?

I am trying to alert the text of a div which is in a for loop when it is clicked. There are many divs with same id, i want to get 3 if i click the 3rd or 2 when 2nd is clicked. How can i make it with the following code or what must i add to it? Thank you.
<? for($i=0; $i<5; $i­­++) { ?>
<div id="abc"><? echo $i ?></div>
<? } ?>
<script>
$(function() {
$("#abc").click(function() {
var thevar= $("#abc").text();
alert (thevar);
}
</script>
Just try to use a class instead of using id inside that loop,
<? for($i=0; $i<5; $i­­++) { ?>
<div class="abc"><? echo $i ?></div>
<? } ?>
<script>
$(function() {
$(".abc").click(function()
{
var thevar= $(this).text();
alert (thevar);
});
});
</script>
You should have unique ids on page. due to this $("#abc").text() always returns value for first element in matched selector. Rather use abc as class. and to refer element in current context, use $(this):
var thevar=$(this).text();
You have syntax error in your code. Missing }); . Id should be unique .
<? for($i = 0;$i<5;$i++) { ?>
<div class="abc"><? echo $i ?></div> //change
<? } ?>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(function() {
$(".abc").click(function()
{
var thevar= $(this).text(); //change
alert (thevar);
});//was missing
});//was missing
</script>

Categories

Resources