how to set value to specific object of array object in javasript - javascript

I have to write inputbox inner a looping statement.
let say I have 3 times loop
<?php
for($i = 0; i<3;i++){
?>
<input type="number" id="numb" onkeyup="getvalue(this.value)"/>
<span id="result"></result>
<?php
}
?>
<script>
function getvalue(val){
var res= parseInt(val)*10;
if(isNaN(res) == true){
res = 0;
}
document.getElementById('result').value = res;
}
</script>
the question is, how to set every value I type in inputbox only settbthe result
inner span from its row index only

You can access the input that the user is typing in it bye getting the event object and the target property of that. That event.target (input element) has a property called nextElementSibling.
Use the nextElementSibling to access the next element after the input which here it is the span.
No need to use id or other methods
Change the input element to:
<input type="number" class="numb" onkeyup="getvalue(event)"/>
Change the script tag content to:
function getvalue(event) {
var input = event.target;
var val = input.value;
var res = parseInt(val) * 10;
if (isNaN(res) == true) {
res = 0;
}
input.nextElementSibling.textContent = res;
}

You might have more luck trying an approach like this. Remove the ID attributes from the elements - you can replace with class names if you like or remove entirely from the span element as it should not necessarily be required to allow you to target it programmatically. If you use sibling selectors you can use the target attribtute of the event ( in this case keyup within the number element ) and then traverse the DOM to find the span...
<?php
for($i = 0; $i<3; $i++){
?>
<input type="number" class="numb" onkeyup="getvalue(event)"/>
<span class="result"></span>
<?php
}
?>
<script>
function getvalue(e){
var node=e.target.nextElementSibling;
var res=parseInt(e.target.value) * 10;
if( isNaN(res) )res=0;
node.textContent=res;
}
</script>
function getvalue(e){
var node=e.target.nextElementSibling;
var res=parseInt(e.target.value) * 10;
if( isNaN(res) )res=0;
node.textContent=res;
}
<input type="number" onkeyup="getvalue(event)" />
<span></span>
<input type="number" onkeyup="getvalue(event)" />
<span></span>
<input type="number" onkeyup="getvalue(event)" />
<span></span>

You can set an id for each input and it related result span. The id will just be the $i of the for loop. This will help to easily access the specified result span in the getvalue function:
<?php
for ($i = 0; $i < 3; $i++) {
?>
<div>
<input type="number" data-input-id="<?php echo $i; ?>" onkeyup="getvalue(this)" >
<span class="result-<?php echo $i; ?>"></span>
</div>
<?php
}
?>
<script>
function getvalue (element) {
const inputId = element.dataset.inputId;
const val = element.value;
let res = parseInt(val) * 10;
res = isNaN(res) ? 0 : res;
document.querySelector(`.result-${inputId}`).innerText = res;
}
</script>

Related

Good way to check all checkboxes in Laravel-blade

Is there any good way to put "All-cheked" button on Blade PHP?
I've tried to control it by JavaScript. However, Each checkbox name is different.
Even I am aware this way seems not a good method.
<script language="JavaScript" type="text/javascript">
function AllChecked(){
var all = document.form.all.checked;
for (var i=0; i<document.form.test.length; i++){
document.form.test[i].checked = all;
}
}
function DisChecked(){
var checks = document.form.test;
var checksCount = 0;
for (var i=0; i<checks.length; i++){
if(checks[i].checked == false){
document.form.all.checked = false;
}else{
checksCount += 1;
if(checksCount == checks.length){
document.form.all.checked = true;
}
}
}
}
</script>
#for ($i = 0; $i < 10; $i++){{$i}}
<div>
{{date('m-d',strtotime($i." day"))}}
<input type="checkbox" name="available_date" value="<?php echo date("Y-m-d", strtotime("{{$i}} day")) ?>">
<button onClick="AllChecked();">ALL Checked </button>
#for ($j = 0; $j < 25; $j++)
<input type="checkbox" name="{{date('Y-m-d',strtotime($i." day"))}}" value="{{$j}}">{{ $j }}:00
#endfor
</div>
Actually you can't control dynamic users behavior by PHP, because PHP works only on server, so all such things are managing by javascript (if I understood you correctly)
Not 100% sure, but seems you don't need both checkbox and button for All Checked
In javascript you can select all checkboxes using a class (will show example with jquery for simplicity)
// html
<input type="checkbox" class="all_checked" name="available_date" value="<?php echo date("Y-m-d", strtotime("{{$i}} day")) ?>">
#for ($j = 0; $j < 25; $j++)
<input type="checkbox" class="checkbox" name="{{date('Y-m-d',strtotime($i." day"))}}" value="{{$j}}">{{ $j }}:00
#endfor
// js
$('.all_checked').on('click', function () {
const allCheckedCheckbox = $(this);
$('.checkbox').each(function () {
$(this).prop('checked', allCheckedCheckbox.prop('checked'));
});
});
You can do this using jquery.
Simply add a common class to each of the checkboxes
ex :- class="checkbox"
And write a js function
function AllChecked(){
$('.checkbox').attr("checked");
}

PHP associative array null in Javascript function

I have a PHP webpage containing 6 textboxes as given below:
<html>
<script type="text/javascript">
function add()
{
//PHP associative array not storing properly in JS array
var array = JSON.parse(<?php echo json_encode($elementsindex); ?>);//getting array
//JS array elements not printing
for(var i in array)
{
alert("key = "+i+" and value = "+array[i]);
}
for(var key in array)
{
if(array[key]===null || array[key]===0)//for loop not executing
{
var valtoadd = 5;
array[key] = valtoadd;//add value to index IN ARRAY
var textbox = document.getElementById(key);
textbox.value = valtoadd;//add value to textbox
}
}
}
</script>
<body>
<form method="POST" action="">
<div id="operation">
<input type="text" id = "5E" name="5E" value="">
<input type="text" id = "4E" name="4E" value="" >
<input type="text" id = "3E" name="3E" value="">
<input type="text" id = "2E" name="2E" value="">
<input type="text" id = "1E" name="1E" value="">
<input type="text" id = "0E" name="0E" value="">
</div>
....rest of the code
</form>
..php code
I have a PHP code in the same page that invokes the Javascript function add() on a particular buttonclick() which is working perfectly:
<?php
include 'footer.php';
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['PUSH']))
{
//I am creating an associative array
$elementsindex = array("0E"=>0 ,"1E"=>0,"2E"=>0, "3E"=>0, "4E"=>0, "5E"=>0);
echo '<script type="text/javascript">';
echo 'add();'; //invoking JS function
echo '</script>';
}
?>
However in the Javascript function add(), the PHP array is not getting stored in var array. Also, the array elements are not printing in the alert box and the code never executes the for(var key in array) loop.
I am sure that the associative array is being passed correctly (the Javascript function is invoked successfully), but maybe not being received at the JS function because initially all the values in the key-value pair are zero (required for the project).
This code stores the $a into an object variable. I simply change the way to obtain the value.
var obj = <?php echo json_encode($a); ?>;
for (var i in obj)
{
alert("key = " + i + " and value = " + obj[i]);
}

Limit number of characters in collection of number input fields

I have used the reference from from this question and I want to achieve exactly what the question asked however for multiple input text fields. I would like to restrict the user to not type further and have used getElementsByClassName instead of getElementById.
HTML
<td>
<input id="quantity_scroll" cart_id="<?php echo $cart_row['id']; ?>" min="1" type ="number" max="99" value="<?php echo $cart_row['quantity'] ;?>" oninput = "checkLength()" class="form-control form-quantity" style=" width: 60px;text-align: left;" >
</td>
Javascript
function checkLength(){
var elements = document.getElementsByClassName("form-quantity");
var y;
var ele = elements.length/2;
for(y=0; y < ele; y++){
var length = elements[y].value.length;
if(length <= 2){
return true;
}else{
var value = elements[y].value;
value = value.substring(0, value.length-1);
document.getElementsByClassName("form-quantity")[y].value = value;
}
}
}
However the user is restricted only in the first input box and not in the others. I tried different ways however cannot understand why it isn't happening.
Check the below code. It will restrict users to not enter more than 3 digit numbers. You just need to ensure that all your input fields have the same class form-field:
$(".form-field").on('input', function() {
var enteredVal = $(this).val();
if (enteredVal.length > 3) {
$(this).val(enteredVal.substring(0, enteredVal.length - 1));
console.log('More than 3 characters not allowed.');
return;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='form-field' />

sum string with number onclick

I have a global variable :
var a;
I put my onclick function into my html div in concatenation PHP :
$number =' <div onclick="select(this,'."'250000'".');" > ';
$number .= ...etc... //php function
$number .='</div>';
to insert string into div value onclick (button) :
function select (price){
if ($(id).attr('class') == "table2") { //unselect button
$(id).attr('class', 'table1');
var price2=document.getElementById("price").value.split(",");
var removePrice = price;;
var price3 = jQuery.grep(price2, function (value) { return value != removePrice;});
document.getElementById("price").value = price3;
if (n.length == 0) i = 0;
} else {
$(id).attr('class', 'table2'); //select button
if (i == 0) {
document.getElementById("price").value = price;
a = Number(document.getElementById("price").value); //assign the value into a
i = 1;
} else {
$(id).attr('class','table3');
}
}
From there, I have checkbox HTML :
<div id="CourseMenu"><input type="checkbox" value="50000" />&nbsp Ekstra Bed <input type="checkbox" value="50000" />&nbsp Breakfast</div>
After that I have another function to sum 2 div value (checkbox) :
$(function($) {
var sum = 0;
$('#CourseMenu :checkbox').click(function() { sum = 0;
$('#CourseMenu :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
var b = parseInt(a||0, 10) + parseInt(sum||0, 10);
$('#sum').html(b); //<--resulted NaN when sum with button
document.getElementById("price").value=b; //<-- assign b as div value
});
});
The purpose is to sum the total price (button & checkbox) into div value
<input type="hidden" id="price" name="price" value="" />
it works fine when the function sum only the checkbox, but when I try to show the sum with the button (global variable) it resulted in NaN
I think I already convert the string into number there, is there something wrong with my code?
I think you have a problem in passing the arguments in onclick event:
onclick="select(this,'250000');" => passing this as first argument try changing to onclick="select('250000')";
but your select function is expecting string as the first argument:
function select(price){ //<-- simplified
document.getElementById("price").value=price;
a = Number(document.getElementById("price").value);
}
Here is an actual solution for your X/Y problem.
The code will initialise the field and clicking buttons or checking checkboxes work independently.
function calc() {
var sum = parseInt($("#price").text(), 10);
$('#CourseMenu :checkbox:checked').each(function() {
sum += parseInt(this.value, 10);
});
$('#sum').val(sum);
}
$(function() {
$("#CourseMenu .btn").on("click", function() {
$("#price").text($(this).data("price")); // using the data attribute
calc();
});
$('#CourseMenu input:checkbox').on("click",function() {
calc(); //
});
calc(); // initialise in case the page is reloaded.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="CourseMenu">
<button type="button" class="btn" data-price="25000">25000</button>
<button type="button" class="btn" data-price="35000">35000</button>
<div id="price">0</div>
<br/>
<label>
<input type="checkbox" value="200" />200</label>
<label>
<input type="checkbox" value="300" />300</label>
<label>
<input type="checkbox" value="400" />400</label>
<br/>
<input type="text" id="sum" value="" />
</form>
PS: If you do nothing else on click of checkboxes, you can write
$('#CourseMenu input:checkbox').on("click",calc);

javascript click function not working on form generated in php

I have a form created using echo command in php. It is being displayed correctly. I have a javascript which detects click on radio button of form and displays the hyperlink/anchor corresponding to each button group, which is not working.
But if I create the form in html only without any php, it works perfectly. please HELP.
Form creation
echo("<form name ='input' action = 'result.php' method = 'POST'>");
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
echo(($i+1)." ".$row[1]."<br>");
echo("
<input type = 'radio' value = $row[2] name = '$i'>$row[2]&nbsp&nbsp&nbsp&nbsp
<input type = 'radio' value = $row[3] name = '$i'>$row[3]<br>
<input type = 'radio' value = $row[4] name = '$i'>$row[4]&nbsp&nbsp&nbsp&nbsp
<input type = 'radio' value = $row[5] name = '$i'>$row[5]&nbsp&nbsp
<a id='$i' href='javascript:clear($i)'>Reset</a><br>");
$i++;
$z[]=$row[6];
}
SCRIPT
$('input:radio').click(function() {
var n = $(this).attr('name');
var k ='#' + n;
alert($(this).attr('name'));
$(k).show(400);
});
You can try changing $('input:radio') to $('input[type="radio"]').
Try this
$('input[type="radio"]').on('click', function() {
var n = $(this).attr('name');
var k ='#' + n;
alert($(this).attr('name'));
$(k).show(400);
});
$('body').on('click','input:radio',(function() {
var n = $(this).attr('name');
var k ='#' + n;
alert($(this).attr('name'));
$(k).show(400);
});
When clicking on dynamically created elements you need to use event delegation.
Hmm... your problem is that $row array should be with curly brackets because you're in double quotes
echo("<form name ='input' action = 'result.php' method = 'POST'>");
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
echo(($i+1)." ".$row[1]."<br>");
echo("
<input type = 'radio' value = '{$row[2]}' name = '$i'>{$row[2]}&nbsp&nbsp&nbsp&nbsp
<input type = 'radio' value = '{$row[3]}' name = '$i'>{$row[3]}<br>
<input type = 'radio' value = '{$row[4]}' name = '$i'>{$row[4]}&nbsp&nbsp&nbsp&nbsp
<input type = 'radio' value = '{$row[5]}' name = '$i'>{$row[5]}&nbsp&nbsp
<a id='$i' href='javascript:clear($i)'>Reset</a><br>");
$i++;
$z[]=$row[6];
}

Categories

Resources