Enable button when select option in PHP using Javascript - javascript

I tried some code from other topics to resolve my problem here but I still don't manage to get what I want..
I need a button to goes enable when the user select one of the item in a select option and goes to disable when the users re-select the default select..
<script text="text/javascript">
$(document).ready(function(){
$('#select_resa').change(function(){
var val = $('#select_resa').val();
alert(val);
if (val == '') {
$('#supprimer_resa_button').attr('disabled', 'disabled');
}else{
$('#supprimer_resa_button').removeAttr('disabled');
}
});
});
</script>
<form method="post" action="modif_resa.php?" id="modif_resa">
<h2>Modifier/Supprimer un reservation</h2>
<?php if(isset($erreur)) echo '<p style="font-style:italic;font-size:0.8em;text-align:center;color:red;margin-bottom:5px;">'.$erreur.'</p>'; ?>
<label for="salle"><strong>Choisissez une reservation</strong></label>
<select id="select_resa" name="select_resa">
<option value="" id="select" name="select">--Selectionnez--</option>
<option value=""></option>
<option value="2">salut</option>
<?php
if(!empty($liste_reservations)){
for($i=0;$i<count($liste_reservations);$i++){
echo '<option "title="'.$liste_reservations[$i]['RS_NOM'].'" value="'.$liste_reservations[$i]['RS_NOM'].'" '.(isset($SALLE) && $SALLE==$liste_reservations[$i]['RS_ID']?'selected="selected"':'').'>'.$liste_reservations[$i]['RS_NOM'].'</option>';
}
}
?>
</select>
<br/><br/>
<label for="s_date"> Modifier la date de fin</label>
<input type="text" value="<?php if(isset($RS_DATE)) echo $RS_DATE;?>" name="s_date" id="s_date" maxlength="10" size="10"/>
<img src="/Libs/calendar/calendar_small.png" alt="Calendrier" style="vertical-align:middle; border:0;" title="Calendrier" />
<br/><br/>
<span class="valider">
<input type="submit" name="valider" value="<?php echo TXT_VALIDER; ?>" />
</span>
<br/><br/>
<div style="text-align:center; margin-top: 50px;">
<input id="supprimer_resa_button" disabled="disabled" type="submit" name="supprimer_resa_button" style="font-size: 15px; width: auto; height:auto; font-weight:bold;" value="<?php echo TXT_SUPPRIMER_RESA; ?>" />
</div>
</form>
My Submit button is enable in any case here...
Where am I wrong ?

Please check this:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script text="text/javascript">
$(document).ready(function(){
$('#select_resa').change(function(){
var val = $('#select_resa').val();
if (val == '') {
$('#supprimer_resa_button').attr('disabled', 'disabled');
}else{
$('#supprimer_resa_button').removeAttr('disabled');
}
});
});
</script>
<form method="post" action="modif_resa.php?" id="modif_resa">
<h2>Modifier/Supprimer un reservation</h2>
<?php if(isset($erreur)) echo '<p style="font-style:italic;font-size:0.8em;text-align:center;color:red;margin-bottom:5px;">'.$erreur.'</p>'; ?>
<label for="salle"><strong>Choisissez une reservation</strong></label>
<select id="select_resa" name="select_resa">
<option value="" id="select" name="select">--Selectionnez--</option>
<option value="1">abc</option>
<option value="2">def</option>
<option value="3">ghi</option>
<?php
if(!empty($liste_reservations)){
for($i=0;$i<count($liste_reservations);$i++){
echo '<option "title="'.$liste_reservations[$i]['RS_NOM'].'" value="'.$liste_reservations[$i]['RS_ID'].'" '.(isset($SALLE) && $SALLE==$liste_reservations[$i]['RS_ID']?'selected="selected"':'').'>'.$liste_reservations[$i]['RS_NOM'].'</option>';
}
}
?>
</select>
<br/><br/>
<label for="s_date"> Modifier la date de fin</label>
<input type="text" value="<?php if(isset($RS_DATE)) echo $RS_DATE;?>" name="s_date" id="s_date" maxlength="10" size="10"/>
<img src="/Libs/calendar/calendar_small.png" alt="Calendrier" style="vertical-align:middle; border:0;" title="Calendrier" />
<br/><br/>
<span class="valider">
<input type="submit" name="valider" value="<?php echo TXT_VALIDER; ?>" />
</span>
<br/><br/>
<div style="text-align:center; margin-top: 50px;">
<input id="supprimer_resa_button" disabled="disabled" type="submit" name="supprimer_resa_button" style="font-size: 15px; width: auto; height:auto; font-weight:bold;" value="<?php echo TXT_SUPPRIMER_RESA; ?>" />
</div>
</form>

You just need to use:
$('#supprimer_resa_button').removeAttr('disabled');
instead of
$('#supprimer_resa_button').attr('disabled', '');

In recent jQuery api, you must use prop on boolean html attributes :
$('#supprimer_resa_button').prop('disabled', false)
Or
$('#supprimer_resa_button').prop('disabled', true)
attr is only with html attributes which can contain a value.
In your case, you can also do a little shorter :
function updateFormEnabled() {
$('#supprimer_resa_button').prop('disabled', verifyAdSettings());
}

Related

How to use ajax to populate input with select option with data from database?

The question I've got in my test goes like so.
You have 1 select with 2 options(item number1 and item number2) and 2 input fields(price,weight). How would you make the input fields change without writing in them?
So after a long time of searching and trying stuff out (without much luck) I've learned that I need to use ajax for this to work. so I have tried a bunch and this is the code I've tried edit so it would work.
getAllproduct is just a select that fetches all the data inside my table with products. this is id, name, item_number, price, weight. anyhow here is my code
<?php
$sth = $db->prepare("SELECT `price`,`weight` FROM product");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$row = array();
json_encode($row);
?>
product.php
<div class="form-group col-2">
<label for="product">Item number</label>
<?=#$error['product']?>
<select class="form-control" name="product" id="product" onChange="getproduct(this.value)">
<?php foreach ($csv->getAllproduct() as $csv) { ?>
<option value="<?= #$csv->id ?>" selected><?= #$csv->product?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-2">
<label for="weight">weight</label>
<?=#$error['weight']?>
<input type="text" name="weight" id="weight" class="form-control">
</div>
<div class="form-group col-2">
<label for="price">price</label>
<?=#$error['price']?>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
<script>
function getproduct(val){
$.ajax({
type:"POST",
url:"pages\call.php",
data: 'product='+val,
success: function(response){
var result = JSON.parse(response);
if (result.response == true) {
var data = result.rows;
$("#weight").val(data[0].weight);
$("#price").val(data[0].price);
}else if (result.response == false) {
$('#product').append('<option>No products were found!</option>');
}
}
});
}
</script>
What I expect to be able to do is select an item number and it will automatically populate the inputfields price and weight with the data inside the database from the item number.
I haven't learned a lot of Ajax/js so Any help is appreciated.
Attempt: on other project using this code. havent gotten it to work yet.
<form class="row" method="POST" >
<div style="border-color:#dddddd;" class="dropdown-divider col-12"></div>
<script>$('#Varenummer').on('change', function() {
var selectedOption = $(this).find('option:selected');
$('#Tolminus').val(selectedOption[0].dataset.Tolminus);
$('#Tolplus').val(selectedOption[0].dataset.Tolplus);
});
</script>
<div class="form-group col-2">
<label for="Varenummer">Varenummer</label>
<?= #$error['Varenummer'] ?>
<select class="form-control" name="Varenummer" id="Varenummer">
<?php
foreach ($csv->getAllVarenummer() as $csv) {?>
<option value="<?= #$csv->id ?>" data-Tolminus="<?= #$csv->Tolminus ?>"
data-Tolplus="<?= #$csv->Tolplus ?>"><?= #$csv->Varenummer ?></option>
<?php }?>
</select>
</div>
<div class="form-group col-2">
<label for="Tolminus">Tol -</label>
<?= #$error['Tolminus'] ?>
<input type="text" name="Tolminus" id="Tolminus" class="form-control" value="">
</div>
<div class="form-group col-2">
<label for="Tolplus">Tol +</label>
<?= #$error['Tolplus'] ?>
<input type="text" name="Tolplus" id="Tolplus" class="form-control" value="">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
the jquery scrips and others are added in the footer.
As you asked above in comments: i need it to the input to change when i select an option. can i still only use php?...
Yes.
You might not need ajax at all. For your task I'd recommend to preload weight and price values into data- attributes of corresponding option elements. Then, on the select change, just get those values and paste them to inputs.
$('#product').on('change', function() {
var selectedOption = $(this).find('option:selected');
$('#weight').val(selectedOption[0].dataset.weight);
$('#price').val(selectedOption[0].dataset.price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-2">
<label for="product">Item number</label>
<select class="form-control" name="product" id="product">
<option disabled selected>Choose product...</option>
<option value="1" data-weight="100" data-price="1000">Product 1</option>
<option value="2" data-weight="50" data-price="200">Product 2</option>
<option value="3" data-weight="25" data-price="115">Product 3</option>
</select>
</div>
<div class="form-group col-2">
<label for="weight">weight</label>
<input type="text" name="weight" id="weight" class="form-control">
</div>
<div class="form-group col-2">
<label for="price">price</label>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
For the PHP generated select (assuming the getAllproduct method returns weight and price properties):
...
<div class="form-group col-2">
<label for="product">Item number</label>
<?=#$error['product']?>
<select class="form-control" name="product" id="product">
<?php foreach ($csv->getAllproduct() as $csv) { ?>
<option value="<?= #$csv->id ?>" data-weight="<?= #$csv->weight ?>" data-price="<?= #$csv->price ?>"><?= #$csv->product?></option>
<?php } ?>
</select>
</div>
...

pass all rows selected option values which is determined by user input from php

How can I pass selected option values if it's randomly generate by user?
How can I get the values of each selected option for each rows if I determined the values?
something like this.
Javascript
<script>
function submitForm(action)
{
document.getElementById('columnarForm').action = action;
document.getElementById('columnarForm').submit();
}
</script>
PHP
<form class="form-horizontal" action="" method="post" id="columnarForm">
<!-- some html tag -->
<?php
if ($_SERVER['REQUEST_METHOD'] =='POST' && isset($_POST['addButton1'])) {
$table = $_POST['selectTable'];
if($table == 'company')
{
$num = $_POST['num'];
for($j = 1; $j <= $num; $j++) {
?>
<tr id="row1">
<td align="right"><?php echo $j; ?></td>
<td id="name_row1" width="2px">
<input type="text" id="new_name" name="text<?php echo $j; ?>" value=""></td>
<td id="country_row1">
<select class="selectField" onChange="" id="selectcom" name="selectcom<?php echo $j; ?>">
<option value="">-- Select Field --</option>
<option value="comp_id<?php echo $j; ?>">comp_id</option>
<option value="comp_name<?php echo $j; ?>">comp_name</option>
</select>
</td>
<td><input type="text" name="default" size="10"></td>
<td id="data_row"><div id="new_text<?php echo $j;?>"></div></td>
<td id="size_row"><div id="size_row<?php echo $j;?>"></div></td>
<td>
<input type="button" value="Delete" class="delete btn btn-small btn-info" onclick="delete_row('row1')">
</td>
</tr>
<?php
}
}
?>
<button type="submit" class="btn btn-primary noty" name="next" onclick="submitForm('import.php')">Create Template</button>
How can I give variable at the next page (import.php)?
sorry for my english imperfections
$('#noc').change(function(e) {
$('.child').remove();
id = $(this).val();
for(var i=1; i<id; i++){
var thisRow = $('.dd').last(".dd");
var newid = parseInt(thisRow.attr('divid'))+1;
newRow = thisRow.clone(true).insertAfter(thisRow).find('input').val('').end().
find('.name').each(function(){
$(this).attr('id', 'name-'+newid);
$(this).attr('name','name-'+(newid));
$(this).attr('placeholder','Name '+(newid));
}).end().find('.drop').each(function(){
$(this).attr('id', 'dd-'+newid);
$(this).attr('name','dd-'+(newid));
}).end();
thisRow.next('.dd').attr("divid",newid).addClass("child");
}
});
div{ display: inline-table;}
<link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><section style="width:40%" align="center">
<form>
<div class="col-md-12"><input type="text" class="form-control" id="noc" /></div>
<div class="dd" divid="1" align="center">
<div class="col-md-6">Field Name</div>
<div class="col-md-6">Column Name</div>
<div class="col-md-6"><input type="text" placeholder="Name 1" class="name form-control" id="name-1" name="name-1" /></div>
<div class="col-md-6">
<select name="dd-1" id="dd-1" class="drop form-control">
<option>value 1</option>
<option>value 2</option>
<option>value 3</option>
<option>value 4</option>
</select>
</div>
</div>
</form>
</section>
Check this code

How to create multiple text area at the time of edit option using PHP and JavSscript

I am creating multiple text area using + button and I need to do the same operation when edit option is also there using PHP and JavaScript. Here is my code:
<div style="width:24%; float:left; padding:10px;">No of questions :
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" value="<?php if($_REQUEST['edit']) { echo $getcustomerobj->no_of_question; } else { echo $_REQUEST['no_of_question']; } ?>" type="text" onkeypress="return isNumberKey(event)">
<div id="err_msg_name" style="font-size:12px; color:#FF0000; text-align: center;"></div>
</div>
<div class="clear"></div>
<div style="padding-bottom:10px;">
Questions : <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();"><input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
</div>
<div id="container">
<div>
<div style="width:24%; float:left; padding:10px;">
<textarea class="form-control" name="questions0" id="questions" placeholder="Questions" style="background:#FFFFFF;" rows="2"><?php if($_REQUEST['edit']) { echo $getcustomerobj->questions; } else { echo $_REQUEST['questions']; } ?></textarea>
</div>
<div style="float:left;margin-top:37px;">
<?php
$status=array("status"=>'1');
$feeddata=$db->kf_answertype->find($ustatus);
?>
<div style="float:left; margin-right:10px;">
<?php
foreach($feeddata as $v){
?>
<input type="radio" name="answer_type0" id="answer_type0" onClick="selectScale(this.value,'0');" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?>
<?php
}
?>
</div>
<div style="float:left; margin-top:-10px;display:none;" id="scaleid0"><select class="form-control" id="nscale0" name="noofscale0">
<option value="">Select Answer Type</option>
<?php
$status=array("status"=>'1');
$feeddata=$db->kf_scale->find($ustatus);
foreach($feeddata as $v){
?>
<option value="<?php echo $v['_id']; ?>" <?php if($getcustomerobj->no_of_scale == $v['_id'] or $_REQUEST['no_of_scale'] == $v['_id']){ print 'selected'; } ?>><?php echo $v['noofscale']; ?></option>
<?php } ?>
</select>
</div>
<div style="clear:both;"></div>
</div>
<div style="clear:both;"></div>
</div>
</div>
</div>
My JavaScript function is given below:
<script>
function addQuestionField(){
var get =$("#ques").val();
if(get==null || get==''){
alert('Please add no of questions');
}else{
var counter = 0;
if (counter > 0){
return;
}else{
counter++;
<?php
$status=array("status"=>'1');
$feeddata=$db->kf_answertype->find($ustatus);
?>
<?php
$status=array("status"=>'1');
$feeddatascale=$db->kf_scale->find($ustatus);
?>
for(var i=1;i<get;i++){
$('#container').append('<div><div style="width:24%; float:left; padding:10px;"> <textarea class="form-control" name="questions'+ i +'" id="questions" placeholder="Questions" style="background:#FFFFFF;" rows="2"><?php if($_REQUEST['edit']) { echo $getcustomerobj->questions; } else { echo $_REQUEST['questions']; } ?></textarea></div><div style="float:left;margin-top:37px;"><div style="float:left; margin-right:10px;"><?php foreach($feeddata as $v){?> <input type="radio" name="answer_type'+i+'" id="answer_type0" onClick="selectScale(this.value,'+i+');" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?> <?php }?></div><div style="float:left; margin-top:-10px;display:none;" id="scaleid'+i+'"><select class="form-control" id="nscale'+i+'" name="noofscale'+i+'"><option value="">Select Answer Type</option><?php foreach($feeddatascale as $v){ ?><option value="<?php echo $v['_id']; ?>" <?php if($getcustomerobj->no_of_scale == $v['_id'] or $_REQUEST['no_of_scale'] == $v['_id']){ print 'selected'; } ?>><?php echo $v['noofscale']; ?></option><?php } ?></select></div><div style="clear:both;"></div></div><div style="clear:both;"></div></div>');
}
}
}
}
function deleteQuestionField(){
var get =$("#ques").val();
var textareas = $('#container textarea');
if (textareas.length !== 0) {
textareas.last().remove();
$('#ques').val(textareas.length - 1);
}
}
</script>
Here I can create the multiple text-area,radio button using + button which depends on no of questions field value. Here I need to do the same thing when the following condition is true.
if($id!='' && $_REQUEST['edit']==1){
}
at the time of page reload if the above condition is true then no need to click on + button, the multiple field should also created.

how to keep $_POST after submitting form with onchange event?

I have a list view and grid view which are submit buttons and I have sort selection if I click on one of the select options the form will be submitted but I want to keep $_POST value whether the list had been clicked or Grid because when I submit the form the data will be gone
I want something like:
Name had been clicked and list had been clicked before that
live example: (I changed it but concept is the same)
I cannot remove onchange submit of select drop down and simply first choose the drop down selection and then submit the buttons because I need it to be like that for when going to the option load the form with new information
The reason why I am submitting on onchange is that I need it because I sort my items with this submit
my question is how can I have them both? do I need two forms? do I need to use jQuery?
or php will do the work?
I kept value of option after submit by javascript but I don't know how to maintain the value of $_POST that which one had been clicked
how can I keep $_POST value when it has been set and submit the form on onchange of sort?
<form method="post" action="">
<div id="gridSort">
<span>View Results As:</span> <span>
<input type="submit" class="listButtons" name="view" value="List"> </span> <span>
<input type="submit" class="resultButtons" name="view" value="Grid"></span>
<select id="sortSelect" class="sortSelect" size="1" name="sort" onchange="this.form.submit();">
<option selected>Sort</option>
<option value="Name">Name</option>
<option value="PriceLowToHigh">Price - Low</option>
<option value="PriceHighToLow">Price - High</option>
</select>
</div>
</form>
<script type="text/javascript">
document.getElementById('sortSelect').value ="<?php if(! $_POST['sort']):?>"Sort"<?php else: echo $_POST['sort']; endif;?>";
</script>
<?php
if(isset($_POST["view"])):
if($_POST["view"]=="Grid")
{
echo "Grid clicked";
echo "<br/>";
}
if($_POST["view"]=="List" )
{
echo "List clicked";
echo "<br/>";
}
endif;
?>
Simply add a hidden field to your form:
<form method="post" action="">
<input name="selected_sort" value="<?php echo !empty($_POST['sort']) ? strip_tags($_POST['sort']) : ''; ?>" />
<input name="selected_view" value="<?php echo !empty($_POST['view']) ? strip_tags($_POST['view']) : ''; ?>" />
<div id="gridSort">
<span>View Results As:</span> <span>
<input type="submit" class="listButtons" name="view" value="List"> </span> <span>
<input type="submit" class="resultButtons" name="view" value="Grid"></span>
<select id="sortSelect" class="sortSelect" size="1" name="sort" onchange="this.form.submit();">
<option selected>Sort</option>
<option value="Name">Name</option>
<option value="PriceLowToHigh">Price - Low</option>
<option value="PriceHighToLow">Price - High</option>
</select>
</div>
</form>
This will allow the data to be sent across in all subsequent form submits
<form method="GET" action="">
<body >
<div id="gridSort">
<span>View Results As:</span> <span>
<input type="submit" class="listButtons" name="view" value="List"> </span> <span>
<input type="submit" class="resultButtons" name="view" value="Grid"></span>
<select id="sortSelect" class="sortSelect" size="1" name="sort" onchange="this.form.submit();">
<option selected>Sort</option>
<option value="Name">Name</option>
<option value="PriceLowToHigh">Price - Low</option>
<option value="PriceHighToLow">Price - High</option>
</select>
</div> </body>
</form>
<script type="text/javascript">
document.getElementById('sortSelect').value ="<?php if(isset( $_GET['sort'])){ echo $_GET['sort']; } ?>";
</script>
<?php
if(isset($_GET["view"])){
if($_GET["view"]=="Grid")
{
echo "Grid clicked";
echo "<br/>";
}
if($_GET["view"]=="List" )
{
echo "List clicked";
echo "<br/>";
}
}
?>
I TRIED TO REWRITE YOUR CODE WORKS FINE, but you need to replace post method with get, this will help user on reference and page refresh as many as he want.
Here is what I did for someone who will become frustrated like me:
<form method="post" action="" id="myform">
<div id="gridSort">
<input type="hidden" name="selected_sort" value="<?php echo !empty($_POST['sort']) ? strip_tags($_POST['sort']) : ''; ?>" />
<input type="hidden" name="selectionList_view" value="<?php echo !empty($_POST['Listview']) ? strip_tags($_POST['Listview']) : ''; ?>" />
<input type="hidden" name="selectionGrid_view" value="<?php echo !empty($_POST['Gridview']) ? strip_tags($_POST['Gridview']) : ''; ?>" />
<span>View Results As:</span> <span>
<input type="submit" class="listButtons" name="Lisview" value="List"> </span> <span>
<input type="submit" class="resultButtons" name="Gridview" value="Grid"></span>
<select id="sortSelect" class="sortSelect" size="1" name="sort" onchange="this.form.submit();" >
<option selected>Sort</option>
<option value="Name">Name</option>
<option value="PriceLowToHigh">Price - Low</option>
<option value="PriceHighToLow">Price - High</option>
</select>
</div>
</form>
<script type="text/javascript">
document.getElementById('sortSelect').value ="<?php if(! $_POST['sort']):?>"Sort"<?php else: echo $_POST['sort']; endif;?>";
</script>
<pre>
<?php print_r($_POST); ?>
</pre>

How to make a textfield Editable when checkbox is checked?

Actually, I have many checkboxes and textfields coming from database through single code. I need that when I check a particular checkbox, then a textfield in front of that checkbox to become editable. How can I do that ?
Here is my PHP code
<div class="my"><?php
while ($ass = mysql_fetch_array($rs)) {?>
<input type="checkbox" name="fees_name[]" id="fee_name" value="<?php echo $ass['fees_name']; ?>" onclick='toggleReadonly(this)'>
<?php echo $ass['fees_name']; ?>
<div style="padding:0px 10px 0px 0px; float: right;">
<input id="fee_amt" class="fee_amt" type="text" placeholder="amt" name="fees_amt[]" >
</div> <br><br><?php
}?>
</div>
and my Javascript
$(document).ready(function(){
$('#fee_name').click(function() {
$('#fee_amt').prop('disabled', !$(this).is(':checked'));
});
});
but it worked on only the first checkbox. Anyone can tell my what can i do for others???
All your text fields that are enabled/disabled have the same id. Try to set a different id inside the loop and in your javascript enable the one according to the checkbox that is checked.
Another way (without using ids) is to set the data attribute in each checkbox:
<div class="my">
<?php $i = 1; ?>
<?php while ($ass = mysql_fetch_array($rs)) { ?>
<input type="checkbox" name="fees_name[]" class="fee_name" data-mycheckbox="<?php echo $i; ?>" value="<?php echo $ass['fees_name']; ?>" onclick='toggleReadonly(this)'>
<?php echo $ass['fees_name']; ?>
<div style="padding:0px 10px 0px 0px; float: right;">
<input id="fee_amt<?php echo $i; ?>" class="fee_amt" type="text" placeholder="amt" name="fees_amt[]" >
</div> <br><br><?php
$i++;
}?>
</div>
And in your js script:
$(document).ready(function(){
$(".fee_name").click(function(event) {
var identifier = $(this).data('mycheckbox');
var input_identifier = "#fee_amt" + identifier;
$(input_identifier).prop('disabled', !$(this).is(':checked'))
});
});
solution by #eyetea also solves the problem with your non-unique ids.
just in case you don't want to rely on any ids:
$(document).ready(function(){
$('input[name="fees_name\\[\\]]"').click(function() {
$(this).next().children(':first').prop('disabled', !$(this).is(':checked'));
});
});
note that this sort of selecting the elements heavily relies on your dom structure and has to be changed accordingly when your html changes.
Here is the working code what you need,
$( "input[type=checkbox]" ).on( "click", function(){
if($(this).is(':checked')) {
$(this).next().prop('disabled', false);
} else {
$(this).next().prop('disabled', true);
}
});
HTML
<input type="checkbox" name="fees_name[]">
<input type="text" disabled="disabled" /><br/>
<input type="checkbox" name="fees_name[]">
<input type="text" disabled="disabled" /><br/>
<input type="checkbox" name="fees_name[]" >
<input type="text" disabled="disabled" /><br />
<input type="checkbox" name="fees_name[]">
<input type="text" disabled="disabled" /><br />
<input type="checkbox" name="fees_name[]">
<input type="text" disabled="disabled" />
JSFIDDLE
If you need to give name then you could use input[name='fees_name[]']as,
$( "input[name='fees_name[]']" ).on( "click", function(){
if($(this).is(':checked')) {
$(this).next().prop('disabled', false);
} else {
$(this).next().prop('disabled', true);
}
});
JSFIDDLE
Use the following code-
<div class="my"><?php
$i=0;
while ($ass = mysql_fetch_array($rs)) {$i++;?>
<input type="checkbox" name="fees_name[]" id="fee_name[<?php echo $i?>]" value="<?php echo $ass['fees_name']; ?>" onChange='if(this.checked){toggleReadonly(this,true);} else{toggleReadonly(this,false)}'>
<?php echo $ass['fees_name']; ?>
<div style="padding:0px 10px 0px 0px; float: right;">
<input id="fee_amt[<?php echo $i?>]" class="fee_amt" type="text" placeholder="amt" name="fees_amt[]" readonly>
</div> <br><br><?php
}?>
JavaScript code
function toggleReadonly(chk_element, status)
{
chk_element_no=chk_element.id.substring(chk_element.id.indexOf('[')+1, chk_element.id.indexOf(']'));
txt_element_id="fee_amt["+chk_element_no+"]";
if(status==true)
document.getElementById(txt_element_id).readOnly=false;
else
document.getElementById(txt_element_id).readOnly=true;
}
check this fiddle.
Check the following similar sample code and execute it-
1.php
<html>
<head>
<script>
function toggleReadonly(chk_element, status)
{
chk_element_no=chk_element.id.substring(chk_element.id.indexOf('[')+1, chk_element.id.indexOf(']'));
txt_element_id="fee_amt["+chk_element_no+"]";
if(status==true)
document.getElementById(txt_element_id).readOnly=false;
else
document.getElementById(txt_element_id).readOnly=true;
}
</script>
</head>
<body>
<div class="my"><?php
$i=0;
while ($i++<=10) {?>
<input type="checkbox" name="fees_name[]" id="fee_name[<?php echo $i;?>]" value="<?php echo $i; ?>" onChange='if(this.checked){toggleReadonly(this,true);} else{toggleReadonly(this,false)}'>
<?php echo $i; ?>
<div style="padding:0px 10px 0px 0px; float: right;">
<input id="fee_amt[<?php echo $i;?>]" class="fee_amt" type="text" placeholder="amt" name="fees_amt[]" readonly>
</div> <br><br><?php
}?>
</div>
</body>
</html>

Categories