How to make an HTML element readonly based on PHP value - javascript

I have this code:
<input type = "text" value = "$va" name = "n"/>
and I want it to be readonly if va is not whitespace. How can I accomplish this?

This should make it so that if $va contains whitespace the field will be readonly.
<?php
$readonly = (!empty($va) && strlen(trim($va)) == 0) ? null : 'readonly';
echo '<input type="text" value="'.$va.'" name = "n" '.$readonly.' />';
However I'm not sure if you also want to include an empty string as "only including whitespace", in which case you could alter the first line to:
$readonly = (strlen(trim($va)) == 0) ? null : 'readonly';

1st Option With Java Script
in javascript you can do it like this:
1st: put an id to your element
<input type = "text" value = "$va" name = "n" id='n'/> //i just made it the same as the name
2nd: get the element with the id of 'n'
<script>
$(document).ready(function(){
var nValue = $("#n").val();
if( nValue != " " ) {
$("#n").prop("readonly",true);
}
});
</script>
2nd Option With PHP
in php, assuming that you are printing your element via php:
//other codes here
<?php $va = "noAWhiteSpace";
$readOnly = "";
if($va != ""){
$readOnly = "readonly";
}
?>
<input type = "text" value = "<?php echo $va; ?>" name = "n" <?php echo $readOnly; ?> />;

here is
<input type = "text" value = "$va" name = "n" <?= ($va != '' || $va == null) ? '' : 'readonly'; ?>/>
check https://www.php.net/manual/en/control-structures.if.php

Related

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

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>

Hide zero values of an empty input(number type)

I have a form that gives me data from database, i have number input type. By default it is "0" showed for empty entries. I want to hide "0" from the field and show the value just if is different of 0.
I tried with the code below but it doesn't work.
<input data-validate="number" value="<?php echo $value; ?>" class="form-control" onload="if(this.value == '0') { this.value = ' '; } " >
Add ternary operator to PHP block instead:
<input data-validate="number" value="<?php echo ($value != '0' ? $value : ''); ?>" class="form-control">
I wrote a minimal php function to do this
function fnB($input){
//function to make values blank in number input boxes
if ($input==0) $r="";
else $r=$input;
return $r;}
?>
So in the form one can then enter
value = <?php echo fnB($value);?>

How to disable a table if two values are equal?

I tried to disable a table by using JavaScript if two input values are equal.
My code:
<script type="text/javascript" charset="utf-8">
function checkEnableTable() {
var totalacceptedload = document.getElementById('totalacceptedload'),
var maximumload = document.getElementById('maximumload'),
tablecoursedistribution = document.getElementById('tablecoursedistribution');
tablecoursedistribution.disabled = (totalacceptedload.value = maximumload.value);
}
window.onload = checkEnableTable;
</script>
What am I doing wrong?
My Html
<input id="totalacceptedload" class ="alert alert-success" value ="<?php if (!isset($count_course_choice)):?><?php else: echo $count_course_choice['contact_hours'];?><?php endif ?>"/>
<input id="maximumload" class ="alert alert-danger" value ="<?php if (!isset($eee_setting)): ?><?php else:echo $eee_setting['maximum_course_choice'];?><?php endif ?>"/>
<table id="tablecoursedistribution" >
</table>
this statement first check both values if equal then assign true to tablecoursedistribution.disabled otherwise false to tablecoursedistribution.disabled
tablecoursedistribution.disabled = (totalacceptedload.value == maximumload.value) ? "true" : "false" ;
You can do it like this:
function checkEnableTable() {
tablecoursedistribution.style.visibility = (totalacceptedload.value == maximumload.value) ? "hidden" : "visible"
}
var totalacceptedload = document.getElementById('totalacceptedload'),
maximumload = document.getElementById('maximumload'),
tablecoursedistribution = document.getElementById('tablecoursedistribution');
window.onload = checkEnableTable;
Here's a fiddle.
I made it so that if you enter two equal values in the box, then click the button, the table is hidden, otherwise it is shown.
HTH

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];
}

Unable to check if a javascript checkbox array element is checked or not?

What is want is - when the checkbox is checked option no. 5 in select list will be selected and when the checkbox is unchecked option no. 0 will be selected in the select list.
The select list and the checkboxes are generated dynamically in the php code as below :
echo "<select name='coupons".$i."' id='coupons".$i."'>";
------- All Options --------
echo "</select>";
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode("myCheckbox[]",<?php echo $i;?>)'>
-----------------------------------------------------------------------------
Solved the second requirement on my own now ..... thanks to all for your inputs
just added the following line in the checkAll() within the for loop
setCCode(children[i],i+1);
The javascript function :
function setCCode(checkbox_name,i)
{
var form_object = document.getElementsByName(checkbox_name+"["+i+"]");
var selname = document.getElementsByName("coupons"+i)[0];
if(form_object.checked) {
selname.selectedIndex = 5;
}
else {
selname.selectedIndex = 0;
}
}
The above issue is solved....... thanks to all
Now what i need to do is when a user checks a checkbox to select or deselect all the dynamically generated checkboxes on the form the above logic should work.
<input type='checkbox' name='checkall' onChange="checkAll(this, 'myCheckbox[]')">
<span class="chkall">Check / Uncheck All</span>
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
The javascript code i am using to select/deselect all checkboxes on form is as below :
function checkAll(parent, field)
{
var children = document.getElementsByName(field);
var newValue = parent.checked;
for (i = 0; i < children.length; i++){
if (children[i].disabled == false) {
children[i].checked = newValue;
}
}
}
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
getElementsByName returns an array of objects. Replace the line with:
var form_object = document.getElementsByName(checkbox_name+"["+i+"]")[0];
You can pass refference to the checkbox itself as a parameter
<input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'>
function setCCode(Sender,i)
{
document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0;
}
If you have a reference to the form that the checkbox is in, and it has a unique name in the form, then you can access it as:
form_object = form.elements[ checkbox_name + "[" + i + "]" ];
and you can also use the ternary operator to make the code more concise:
selname.selectedIndex = form_object.checked? 5 : 0;
Edit
Sorry, missed the obvious. If you pass a refereference to the checkbox in the handler, then you can also get the form (all form controls have a form property that references the form they are in). So as Jan Pfeifer suggested (abbreviated markup):
<input ... onclick='setCCode(this, <?php echo $i;?>)'>
then the script is just:
function setCCode(checkbox, i)
{
checkbox.form.elements['coupons' + i].selectedIndex = checkbox.checked? 5 : 0;
}

Categories

Resources