How can i get the different value with code snippets below - javascript

I am having a problem on this because I always get the first value even if I click the last element of the table.
<table>
<?php
for($i=1;$i<=5;$i++){
?>
<tr>
<td><input type="text" id="testId" value="{$i}"><td>
<td><button class="testButton">Click Me</button></td>
</tr>
<?php
}
?>
</table>
for js file
$(document).ready(function(){
$( ".testButton" ).click(function(){
var a = document.getElementById("testId").value;
alert(a);
});
});
how can I get each value?

Don't forget that you actually need to echo $i on the value. And its also important to close the <td> markup properly.
<table>
<?php for($i=1;$i<=5;$i++){ ?>
<tr>
<td><input type="text" class="testClass" value="<?php echo $i; ?>"></td>
<td><button class="testButton">Click Me</button></td>
</tr>
<?php } ?>
</table>
Then on JS, just traverse the previous <td> to get the input values:
$(document).ready(function(){
$('.testButton').click(function(e){
var a = $(this).parent().prev('td').children('input.testClass').val();
alert(a);
});
});
Sample Output

you can assign id for only one element.
in this case, you may want to assign different ids like below.
<td><input type="text" id="testId{$i}"><td>
<td><button class="testButton" data-target="#testId{$id}">Click Me</button></td>
$(document).ready(function(){
$( ".testButton" ).click(function(){
var target = $(this).data("target");
var a = $(target).val();
alert(a);
});
});

Related

Set value of HTML element from javascript

I am using session variable to keep track of items in the cart. I generate a table using loop to display contents of the cart. The code for table is as follow:
<?php
$count=0;
$grandTotal=0;
foreach($_SESSION['cart'] AS $product) {
$table=$product['table'];
$id=$product['id'];
$Name=$product['name'];
$qty=$product['quantity'];
$price=$product['price'];
$total=$qty*$price;
$grandTotal +=$total;
?>
<tr>
<td class="cart_product">
<img src=<?php $i=2; echo "images/".$table."/".$id.".jpg"?> height="150" width="150">
</td>
<td class="cart_description">
<h4><?php echo $Name?></h4>
<p><?php echo "Web ID: ".$id?></p>
</td>
<td class="cart_price">
<p><?php echo $price?></p>
</td>
<td class="cart_quantity">
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" id="increment"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" id="qty" value="<?php echo $qty?>" autocomplete="off" size="2">
<!-- <p class="cart_quantity_input" name="qunatity" id="qty"><?php echo $qty?></p>-->
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" > - </a>
</div>
</td>
<td class="cart_total">
<p class="cart_total_price"><?php echo $total ?></p>
</td>
<td class="cart_delete">
<a class="cart_quantity_delete" href="addToCart.php?table=men&action=del&id=<?php echo $id ?>"><i class="fa fa-times"></i></a>
</td>
</tr>
<?php
}
$tax=0.15*$grandTotal;
?>
I am having problem with + and - buttons within a tags. I want to increment or decrement value in input field named quantity. But since i am generating table in a loop i do not know the id of each field. I want to do something like this:
<script>
$(document).ready(function () {
$("#increment").click(function () {
var oldval=document.getElementById("qty").value;
var newval=parseInt(oldval);
document.getElementById("qty").value=newval++;
});
});
</script>
But this method always increments first quantity field in the table. How do i get ids of other quantity fields in the table?
Dont use ids inside loop.Just use class for that>check the snippet for a smaple demo
$(document).ready(function () {
$(".increment").click(function () {
var oldval = $(this).prev('.qty').val();
var newval = parseInt(oldval)+ 1;
$(this).prev('.qty').val(newval);
});
$(".decrement").click(function () {
var oldval = $(this).next('.qty').val();
var newval = parseInt(oldval) - 1;
$(this).next('.qty').val(newval);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <tr>
<td>sl No</td>
<td>name</td>
<td>Dept</td>
<td>dummy</td>
<td>dummy</td>
<td>dummy</td>
</tr>
<tr>
<td>1</td>
<td>name</td>
<td>
</td>
<td>name</td>
<td>name</td>
<td> </td>
</tr>
<tr>
<td>2</td>
<td>name</td>
<td>Dept</td>
<td>name</td>
<td> <button class="decrement"> - </button>
<input type="text" class="qty" value="1"/>
<button class="increment">+ </button>
</td>
<td>name</td>
</tr>
<tr>
<td>3</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
<td>name</td>
</tr>
</table>
There are 2 solutions to this problem:
When generating table using php, assign unique id to each row's <a> and <input>, such as #increment_id8878 and #input_id8878. Then when #increment or #decrement button is clicked, operate <input> with corresponding id.
Operate <input> element with jQuery's relative selector.
For example:
$('.increment').click(function() {
var inputEle = $(this).siblings('input');
var originVal = inputEle.val();
inputEle.val(parseInt(originVal) + 1);
});
A jsfiddle is made for the 2nd solution.
BTW, duplicate id should be avoided in HTML code.
Don't use same id for multiple elements instead use class like below
<a class="cart_quantity_up" href="addToCart.php?table=<?php echo $table ?>&action=inc&id=<?php echo $id ?>" class="increment">
same is case of decrement button user class
<a class="cart_quantity_down" href="addToCart.php?table=men&action=dec&id=<?php echo $id ?>" name="decrement" class="decrement"> - </a>
You can bind click event to these anchors and change the quantity in input inside same parent div
$(function(){
$('.increment').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)+1;
$input.val(value);
});
$('.decrement').on('click', function(){
var $parent = $(this).closest('.cart_quantity_button');
var $input = $parent.find('.cart_quantity_input');
var value = $input.val();
value = parseInt(value)-1;
$input.val(value);
});
});

Checked all Radio button then get "first td" value of their respective rows, then put on value of all first td in url right after i click submit

"my js"
$(".hit").click(function(){
value = $(this).closest('tr').children('td:first').text();
location.href = "guestdetails.php?id=" + value;
});
"my php"
foreach ($query1 as $flights) {
echo "<tr>";
echo "<td>".$flights['id']."</td>";
echo "<td>".$flights['depart']."</td>";
echo "<td>".$flights['arrive']."</td>";
echo "<td>".$flights['airport']."</td>";
echo "<td>".$flights['duration']."</td>";
echo "<td><label for=lbl3> <input type='radio' checked id='lbl3' name='flight1[]' class='hit1' value='".$flights['flyonly']."'> PHP ".number_format($flights['flyonly'])."</label></td>";
echo "<td><label for=lbl4> <input type='radio' checked id='lbl4' name='flight1[]' class='hit1' value='".$flights['flybaggage']."'>PHP ".number_format($flights['flybaggage'])."</label></td>";
echo "</tr>";
}
HERE'S MY OUTPUT. I ALERT IT JUST FOR NOW
The problem here is when i clicked the radio button it redirect to the guestdetails.php?id... what i need is to fill-up other radio buttons first and send all the value of first TD onto url right after i click the submit button so that i can use $_GET method to echo it out.
ADVANCE THANKS.IM BEGGINER PLS HELP.
You can try this:
$(".hit").click(function(){
var str="";var counter=0;
$.each($("input[name^='flight']:checked").closest("td").siblings("td:first-child"),
function () {
if(counter != 0 )
str +="&";
str +="id"+(counter+1)+"=" + $(this).text();
counter++;
});
console.log(str);
//location.href = "guestdetails.php?" + str;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>f</td>
<td>f</td>
<td><input type="radio" name="flight1[]"></td> <!-- FIND THIS -->
</tr>
<tr>
<td>f1</td>
<td>f</td>
<td><input type="radio" name="flight2[]"></td> <!-- FIND THIS -->
</tr>
<tr>
<td>f2</td>
<td>f</td>
<td><input type="radio" name="flight3[]"></td> <!-- FIND THIS -->
</tr>
</table>
<button type="button" class="hit">hit</button>

Submit button with 2 actions depends on dropdown menu

I am trying to figure out how to submit button with two actions based on dropdown list that I get from MySQL. One is for updating to database and then proceed to nextpage while the other actions is to proceed to specific page. I've tried all the solution but most of them only has a few dropdown menu, mine have 40 menus.
This is my JavaScript
<script type='text/javascript'>
$(window).load(function(){
//$(document).ready(function() {
<!--To Enable button "MULA"-->
$('#lst_respon').change(function() {
if ($(this).find(":selected").val()!='11') {
$('#button').attr('disabled',true);
} else {
$('#button').removeAttr('disabled');
}
});
$('#lst_respon').change(function()
{
$('#form1').submit();
});
});
function changeTextBox()
{
var val=$('#lst_respon').val();
if(val==='11')
{
$('#value').prop('disabled', true);
}
else{$('#value').removeAttr("disabled");}
}
</script>
And this is my HTML
<div align="center">
<table width="60%" border="1" class="zui-table">
<thead>
<tr>
<th colspan="3" align="center">Status</th>
</tr>
</thead>
<tr>
<?php
$smt = $conn->prepare('select * From lookup_caraterima');
$smt->execute();
$data = $smt->fetchAll();
$smt2 = $conn->prepare('select * From lookup_kodrespon');
$smt2->execute();
$data2 = $smt2->fetchAll();
?>
<td width="253">Cara Terima</td>
<td width="5">:</td>
<td width="164">
<select name="lst_cterima" id="lst_cterima">
<?php foreach ($data as $row): ?>
<option value="<? echo $row["kodterima"];?>"><? echo $row["jenis"];?>
</option>
<?php endforeach ?>
</select>
</td>
</tr>
<tr>
<td>Kod Respon</td>
<td>:</td>
<td>
<select name="lst_respon" id="lst_respon" onchange="changeTextBox()">
<?php foreach ($data2 as $row2): ?>
<option value="<? echo $row2["kod"];?>"><? echo $row2["kod"].'- '.$row2 ["Keterangan"];?></option>
<?php endforeach ?>
</select></td>
</tr>
<tr>
<td><label for ="sebab">Sebab</label></td>
<td>:</td>
<td><input type="textbox" id="value" size="100" disabled</td>
</tr>
<tr>
<td colspan="3" align="center"><form name="form1" method="post" action="main.php?load=4&SerialID=<?php echo $noSiri; ?>&month=<?php echo $monthA;?>&year=<?php echo $yearA;?>&tab=A">
<input type="submit" name="button" id="button" value="Teruskan" class="myButton">
</form></td>
</tr>
</table>
</div>
For an automated solution to submit a form based a dropdown selection, you could try using the data attribute, something like:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<form id="tester">
<select name="test">
<option value="best" data-instructions='<?php echo json_encode(array('action'=>'page1')); ?>'>Best</option>
<option value="rest" data-instructions='<?php echo json_encode(array('action'=>'page2')); ?>'>Rest</option>
<option value="guest" data-instructions='<?php echo json_encode(array('action'=>'page3')); ?>'>Guest</option>
<option value="lest" data-instructions='<?php echo json_encode(array('action'=>'page4')); ?>'>Lest</option>
</select>
<input type="submit" name="submit" value="SUBMIT" />
</form>
<script>
$(document).ready(function() {
$('#tester').submit(function(e) {
// Stop form from submitting
e.preventDefault();
// Get the select dropdown
var thisSelect = $(this).find('select[name=test]');
// Get the value
var thisVal = thisSelect.val();
// Get the options separately
var thisOpts = thisSelect.children();
// Create a holder
var thisData = {};
// Loop through the options
$.each(thisOpts,function(k,v) {
// Get the current value
var currVal = $(v).attr('value');
// If the current value is the same as the value selected
if(currVal == thisVal) {
// Get the instructions from the option
thisData = $(v).data('instructions');
// Stop looping
return false
}
});
console.log(thisData);
});
});
</script>
On submission, the selection will give you an object that you can use to instruct how to submit the form:
// thisData.action
{action: "page2"}

Echo PHP Variable to Button Value Then Send Button Value to Input text

Hello I am wanting to echo a PHP Variable to a buttons value then send the buttons value to an input text. I was able to echo the button with the variable but when I click the button it does nothing. I'm not sure why, because when I do this without the PHP just the script, and inputs it works perfectly. I am just missing something I know it, I can't find much info on how to pass php to a button then pass the button value to an input text.
Here's the script that passes the button value to the input text:
$( document ).ready(function() {
var $theButtons = $(".button");
var $theinput = $("#theinput");
$theButtons.click(function() {
$theinput.val(this.value);
});
});
Here's the PHP that echos the variable as a button:
require "config.php"; // database connection
$in=$_GET['txt'];
if(!ctype_alnum($in)){ //
echo "Search By Name, or Entry ID";
exit;
}
$msg="";
$msg="";
if(strlen($in)>0 and strlen($in) <20 ){
$sql="select name, entry, displayid from item_template where name like '%$in%' LIMIT 10"; // the query
foreach ($dbo->query($sql) as $nt) {
//$msg.=$nt[name]."->$nt[id]<br>";
$msg .="<table style='table-layout:fixed;'> // Just the start of my table
<tr>
<td>Name</td>
<td>Entry ID</td>
<td>Display ID</td>
</tr>
<tr>
<td align=center><a href=http://wowhead.com/item=$nt[entry]>
$nt[name]</a>
</td>
<td>$nt[entry]</td>
<td>
<input type=button class=button value=$nt[displayid]> // The Value I need echoed out in a button is $nt[displayid]
</td>
</tr>
</table>"; // end of my table}
}
$msg .='';
echo $msg;
Not that it matters but here is the input text
<input type="text" id="theinput"/>
Make it easy on yourself and try to make your code easy to read. I personally prefer to write my html cleanly and outside of echo statements like so:
Html
if (strlen($in) > 0 and strlen($in) < 20) {
$sql = "select name, entry, displayid from item_template where name like '%{$in}%' LIMIT 10"; // the query
foreach ($dbo->query($sql) as $nt) {
//$msg.=$nt[name]."->$nt[id]<br>";
?>
<table style="table-layout:fixed;">
<tr>
<td>Name</td>
<td>Entry ID</td>
<td>Display ID</td>
</tr>
<tr>
<td align="center">
<?=$nt['name'];?>
</td>
<td><?=$nt['entry'];?></td>
<td>
<input type="button" class="button" value="<?=$nt['displayid'];?>">
</td>
</tr>
</table>
<?php
}
}
Javascript
$( document ).ready(function() {
var $theButtons = $(".button");
var $theinput = $("#theinput");
$theButtons.click(function() {
// $theinput is out of scope here unless you make it a global (remove 'var')
// Okay, not out of scope, but I feel it is confusing unless you're using this specific selector more than once or twice.
$("#theinput").val(jQuery(this).val());
});
});
Ok, here goes...
Use event delegation in your JavaScript to handle the button clicks. This will work for all present and future buttons
jQuery(function($) {
var $theInput = $('#theinput');
$(document).on('click', '.button', function() {
$theInput.val(this.value);
});
});
Less important but I have no idea why you're producing a complete table for each record. I'd structure it like this...
// snip
if (strlen($in)>0 and strlen($in) <20 ) :
// you really should be using a prepared statement
$sql="select name, entry, displayid from item_template where name like '%$in%' LIMIT 10";
?>
<table style="table-layout:fixed;">
<thead>
<tr>
<th>Name</th>
<th>Entry ID</th>
<th>Display ID</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbo->query($sql) as $nt) : ?>
<tr>
<td align="center">
<?= htmlspecialchars($nt['name']) ?>
</td>
<td><?= htmlspecialchars($nt['entry']) ?></td>
<td>
<button type="button" class="button" value="<?= htmlspecialchars($nt['displayid']) ?>"><?= htmlspecialchars($nt['displayid']) ?></button>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endif;

Get id from multiple checkbox when clicked

I want to get current id on click.and checked only one checkbox. Here are my input boxes
<table style="width: 500px; border: 1px solid BLACK;">
<?php for($i=1; $i<10; $i++){ ?>
<tr><td><input type="checkbox" name="myCheckboxes[]" class="chkTag" id="chkBox<?php echo $i; ?>" /></td>
<td><input type="checkbox" name="myTagCheckboxes[]" class="chkTag" id="chkBox<?php echo $i; ?>" value=""/></td>
<td><?php echo $i;?></td></tr>
<?php }?>
</table>
Here is my jQuery
$(document).ready(function(e){
$('input#chkBox1').on('change', function() {
$('input#chkBox1').not(this).prop('checked', false);
});
});
its work for first one. I didn't get the other id on click.
$(document).ready(function(e){
$('input').on('click', function(e){
var id = e.target.id;
$('input#'+id).on('change', function() {
$('input#'+id).not(this).prop('checked', false);
});
});
});
FIDDLE HERE
http://jsfiddle.net/spydo9s3/
The code you have there is targeting one checkbox (ID: chkBox1). Your PHP is ID'ing them dynamically, so chkBox1, chkBox2 etc.
Perhaps what you want is a more dynamic click listener, such as:
$(document).ready(function(e)
{
$('input.chkTag').on('change', function()
{
$('input.chkTag').not(this).prop('checked', false);
});
});
This would target the class that each input shares instead.
IDs must be unique! You must change in your PHP so that each input gets a unique ID not same as any else.
Something like:
<?php for($i=1; $i<10; $i++){ ?>
<tr><td><input type="checkbox" name="myCheckboxes[]" class="chkTag" id="chkBox_0_<?php echo $i; ?>" /></td>
<td><input type="checkbox" name="myTagCheckboxes[]" class="chkTag" id="chkBox_1_<?php echo $i; ?>" value=""/></td>
<td><?php echo $i;?></td></tr>
<?php }?>
And in the jQuery you need not more than:
$('input.chkTag').on('change', function(){
var id = this.id;
// do something with id
});
If you just want one of them checked at time then you need not type="checkbox" but type="radio"

Categories