Using SQLite I can list the values in
<div class="text-middle">
<?php foreach($result as $row) ?>
<button class="button button1" id="myBtn" value="<?php echo $row['Id']; ?>" onclick="myFunction()"><?php echo $row['Id']; ?></button>
<?php } ?>
</div>
However when I click on the button it's showing the only the first value in popup alert.
function myFunction() {
var x = document.getElementById("myBtn").value;
alert(x);
}
How can I get the corresponding values in each button?
All of your buttons have the same id attribute. they must be unique within the page. To fix this you can remove the id attribute and pass the reference of the button to the function:
<div class="text-middle">
<?php foreach($result as $row) { ?>
<button class="button button1" value="<?php echo $row['Id']; ?>" onclick="myFunction(this)"><?php echo $row['Id']; ?></button>
<?php } ?>
</div>
function myFunction(el) {
var x = el.value;
console.log(x);
}
Better still would be to place the same class on all the buttons and use unobtrusive JS code to attach your event handler, like this:
<div class="text-middle">
<?php foreach($result as $row) { ?>
<button class="button" value="<?php echo $row['Id']; ?>"><?php echo $row['Id']; ?></button>
<?php } ?>
</div>
// native JS:
var buttons = document.getElementsByClassName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
var x = this.value;
console.log(x);
});
}
// jQuery:
$('.button').click(function() {
var x = this.value;
console.log(x);
});
Do not use the same id for more then one element: id="myBtn"
Change your function:
onclick="myFunction()"
to:
onclick="myFunction(this)"
And so:
function myFunction(element) {
var x = element.value;
alert(x);
}
You need to get the elements by their class, not by the id that they all share (which is a bad thing to do).
<script>
function myFunction() {
var x = document.getElementsByClassName("button1");
for (var i = 0; i < x.length; ++i) {
alert(x[i].value);
}
}
</script>
Related
I need some help to apply js code for all elements, but for now works only for first on each page.
On page are items with buy buttons, that is created by script, so all buttons have same id but is more than one of them - and I can't apply script that disable button if some condition, only work for first button.
<?php $elem = getElement('button_basket'); ?>
<button disabled = "true" onclick = "checkInput(event)" id="b1" class="btn btn-warning btn-lg btn-block tobasket <?php echo $elem['content_tr'] ?>" product_id="<?php echo $v['id']; ?>" name="<?php echo $prdata['full_name'] ?>" nametr="<?php echo $prdata['name1_tr'] ?>" url="<?php echo $cur_url; ?>catalog/<?php echo $v['img_url']; ?>" price="<?php echo $v['price']; ?>" <?php if($v['sold']==1) echo 'sold="true"'; ?>><?php echo $elem['content'] ?></button>
<?php $elem = getElement('button_oneclick'); ?>
<p class="prod-oneclick <?php echo $elem['content_tr'] ?>" <?php if($v['sold']==1) echo 'sold="true"'; ?>><?php echo $elem['content'] ?></p>
<script type="text/javascript">
function checkInput(event){
<?php
$cookie_basket = $_COOKIE['basket'];
$tempo = urlencode($cookie_basket);
$countChars = mb_strlen($tempo);
//echo $countChars;
?>
let test = '<?php echo $countChars;?>';
let btncheck = document.querySelectorAll('[disabled]');
// var step;
// for (step = 0; step < 5; step++) {
if (test > 80){
document.getElementById("b1").disabled = true;
}else{
document.getElementById("b1").disabled = false;
}
}
// window.onload = checkInput(event);
// }
</script>
if will need can provide full page script.
You should use data attributes and delegation
Also your script can be vastly simplified
let test = '<?php echo $countChars;?>';
window.addEventListener("load", function() {
[...document.querySelectorAll('[disabled]')].forEach(btn => btn.disabled = test > 80)
});
<?php
$cookie_basket = $_COOKIE['basket'];
$tempo = urlencode($cookie_basket);
$countChars = mb_strlen($tempo);
?>
<button disabled class="btn btn-warning btn-lg btn-block tobasket <?php echo $elem['content_tr'] ?>" data-product_id="<?php echo $v['id']; ?>" name="<?php echo $prdata['full_name'] ?>" data-nametr="<?php echo $prdata['name1_tr'] ?>" data-url="<?php echo $cur_url; ?>catalog/<?php echo $v['img_url']; ?>"
data-price="<?php echo $v['price']; ?>" <?php if($v[ 'sold']==1) echo 'data-sold="true"'; ?>><?php echo $elem['content'] ?></button>
<p class="prod-oneclick <?php echo $elem['content_tr'] ?>" <?php if($v[ 'sold']==1) echo 'data-sold="true"'; ?>>
<?php echo $elem['content'] ?>
</p>
Final code, fully working for me was:
<script>
function beCheerful() {
<?php
$cookie_basket = $_COOKIE['basket'];
$tempo = urlencode($cookie_basket);
$countChars = mb_strlen($tempo);
?>
let test = '<?php echo $countChars;?>';
window.addEventListener("DOMContentLoaded", function() {
[...document.querySelectorAll('[disabled]')].forEach(btn => btn.disabled = test > 80)
});
}
for (var i = 0; i < 1; i++) {
beCheerful();
}
window.onload = beCheerful;
</script>
I have obtained a resultset from a query and have count variable which is used to assign id to an input tag. Now i want to pass this id as parameter to a javascript function and increment/decrement the text input field value which has id assigned by the count variable value.
query used to get result:
for (some condition){
$cartsql = "SELECT * FROM products WHERE id=$key";
$cartres = mysqli_query($connection, $cartsql);
$cartr = mysqli_fetch_assoc($cartres);
++$count;
<div class="entry value-minus1" onclick="decrement(<?php echo $count; ?>)"></div>
<input class="entry value1" type="text" value="<?php echo $value['quantity']; ?>" id="<?php echo $count; ?>" />
<div class="entry value-plus1" onclick="increment(<?php echo $count; ?>)"></div>
<!--quantity-->
<script>
function decrement(<?php echo $count; ?>) {
alert("hello");
var y = document.getElementById(<?php echo $count; ?>).value;
y = y - 1;
document.getElementById(<?php echo $count; ?>).value = y;
}
</script>
}
First off, there's a typo in the first div. You forgot to echo the value. Change:
onclick="decrement(<?php $count; ?>)"
to
onclick="decrement(<?php echo $count; ?>)"
Then, since you're passing the id as an argument to your js functions, you shouldn't hard code the values in that function.
You also need to output the javascript after your loop or you will create multiple functions with the same name which, obviously, won't work.
Change it to:
function increment(id) {
document.getElementById(id).value++;
}
function decrement(id) {
document.getElementById(id).value--;
}
Now there's no hard coded values in your function so you can reuse it.
You don't need to use id attributes - a purely integer based id is not valid anyway ( or wasn't until HTML5 ). You can use sibling selectors for convenience. As demonstration the javascript functions can be radically altered / simplified
<style>
div.entry{ display:inline-block;width:2rem;border:1px solid black; height:2rem; line-height:2rem; text-align:center; font-size:1rem; clear:none; cursor:pointer; }
input[type='text']{display:inline-block;height:2rem; }
</style>
<script>
function decrement(e){
e.target.nextElementSibling.value--;
}
function increment(e){
e.target.previousElementSibling.value++;
}
</script>
for( $i=1; $i < 10; $i++ ){
$value=mt_rand(20,50);
echo "
<div>
<div class='entry value-minus1' onclick='decrement(event)'>-</div>
<input class='entry value1' type='text' value='$value' />
<div class='entry value-plus1' onclick='increment(event)'>+</div>
</div>";
}
Better yet would be to remove any inline function calls and use an externally registered event handler - this keeps the HTML nice and clean and separates HTML and javascript.
<script>
document.addEventListener('DOMContentLoaded',()=>{
document.querySelectorAll('div.entry').forEach( div=>{
div.addEventListener('click',function(e){
switch( this.dataset.dir ){
case 'increment':
this.previousElementSibling.value++;
break;
case 'decrement':
if(this.nextElementSibling.value > 0) this.nextElementSibling.value--;
break;
}
});
})
});
</script>
for( $i=1; $i < 10; $i++ ){
$value=mt_rand(5,50);
echo "
<div>
<div class='entry value-minus1' data-dir='decrement'>-</div>
<input class='entry value1' type='text' value='$value' />
<div class='entry value-plus1' data-dir='increment'>+</div>
</div>";
}
i have dynamic number of checkboxes and a button to post the checked elements to another page .. here is the code:
<div class="overSelect"></div>
<div id="checkboxes<?php echo $aa['id']; ?>">
<?php
$pid = select::property($aa['name']);
$arr2 = select::properties($pid);
$cc = 1;
foreach ($arr2 as $aa2) { ?>
<div style="padding-right: 20px" class="row"><label>
<input type="checkbox" value="<?php echo $aa2['name'] ?>" name="checks<?php echo $aa['id'] ?>[]"id="check<?php echo $aa['id']; ?>"><?php echo $aa2['name'] ?>
</label></div>
<?php } ?>
</div>
<a class="btn btn-primary btn-sm" name="update-all"onclick="update_all('prop_id<?php echo $aa['id']; ?><?php $counter; ?>','checks<?php echo $aa['id'] ?>')"id="btn-all<?php echo $aa['id']; ?><?php $counter; ?><?php echo $p['id']; ?>">save</a>
i tried this code but it is not working
<script type="text/javascript">
function update_all(a, b) {
var aa = document.getElementById(a).value;
var values = new Array();
$("input:checkbox[name=b]").each(function () {
if ($(this).is(":checked")){
values.push($(this).val());
}
});
alert(aa);
alert(values.length);
alert(values);
}
</script>
if the checkboxes checked .. it's value will be added to the array and posted to php page
any help please .. thanks in advance
I would like to pass a var from PHP to Javascript. I did this but it does not work. Can someone help me? If you tell me where I'm wrong I learn.
<script>
var passo = <?php echo 'hello'; ?>;
</script>
<button type="button" onclick="funzionepassaggio(passo)" class="btn btn-info btn-lg" data-toggle="modal" data-target="#ModalSubmit"><?php echo "empty"; ?></button>
<script>
function funzionepassaggio(pass) {
alert("hello" + pass);
}
</script>
The answer is hello undefined.
I have one other question! The variable that I have to pass is located within a loop, and of course he always passes the last value! How can I do so that has passed the value that the variable at that time? This is the code:
for ($a = 0; $a < 2; $a = $a + 1) {
?>
<td>
<script>
var passo = "<?php echo $rigauno->nome; ?>";
</script>
<button type="button" onclick="funzionepassaggio(passo)" class="btn btn-info btn-lg" data-toggle="modal" data-target="#ModalSubmit"><?php echo "vuoto"; ?></button>
</td>
<?php } ?>
you need to incude the quotes, so it will be valid string:
<script>
var passo = "<?php echo 'hello'; ?>";
</script>
or better call json_encode that will convert whatever you pass as JSON:
<script>
var passo = <?php echo json_encode($data); ?>;
</script>
json_enocde variable which you want to pass
<script>
var passo = <?php echo json_encode('hello'); ?>;
</script>
$pass='your string or your value ';
<button type="button" onclick="funzionepassaggio('<?php echo $hello; ?>')" class="btn btn-info btn-lg" data-toggle="modal" data-target="#ModalSubmit"><?php echo "empty"; ?></button>
<script>
function funzionepassaggio(pass) {
alert("hello" + pass);
}
</script>
I have created a form in yii and tried using the append method. In said form the user selects the items and enters the amount. If they click the button it will call the function. In output it shows "object text". How do I retrieve it?
<script type="text/javascript">
function myfunction ()
{
var newElem = document.createElement ("div");
newElem.innerHTML =document.createTextNode(amount);
newElem.style.color = "red";
var container = document.getElementById ("new");
container.appendChild (newElem);
}
</script>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'travel1-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name',array('name'=>'name'),array('class'=>'addtocarts')); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Seattype'); ?>
<?php echo $form->dropDownList($model,'seattype',
array('S' => 'Sleeper', 'M' => 'Semi-sleeper','A'=>'Seater'),
array('empty' => '(Select Type)','name'=>'seattype'));?>
<?php echo $form->error($model,'seattype'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'amount'); ?>
<?php echo $form->textField($model,'amount',array('name'=>'amount')); ?>
<?php echo $form->error($model,'amount'); ?>
</div>
</div>
<?php echo CHtml::submitButton('Submit',array('name'=>'submit'))?>
<?php echo CHtml::htmlButton('AddtoCart',array('name'=>'addtocart','onclick'=>'myfunction();'))?>
<div id="new">
</div>
<?php $this->endWidget(); ?>
</div>
Please change your js function like below,
<script>
function myfunction ()
{
var container = document.getElementById ("new");
var newElem = document.createElement ("div");
newElem.innerHTML =$('#amount').val();
newElem.style.color = "red";
container.appendChild (newElem);
}
</script>
this amount textfield should include "id",
<div class="row">
<?php echo $form->labelEx($model,'amount'); ?>
<?php echo $form->textField($model,'amount',array('name'=>'amount','id'=>'amount')); ?>
<?php echo $form->error($model,'amount'); ?>
</div>
You need to get the amount from the textfield and then after creating the text node, append it to the newElem.
function myfunction() {
var amount = document.getElementById('amount').value; // amount value from textfield
var newElem = document.createElement("div");
newElem.appendChild(document.createTextNode(amount));
/* You can also use innerHTML instead of the above line like this newElem.innerHTML = amount; */
newElem.style.color = "red";
var container = document.getElementById("new");
container.appendChild(newElem);
}
<div id="new"></div>
<input type="text" id="amount" />
<button onclick="myfunction()">Click</button>