Loop onchange function to manipulate the target class name - javascript

I used php and jquery. I have to generate multiple select tag depends on the value of condition. I need to manipulate both html,php and and jquery by using loop but I can't find the answer for this to work.
php html code... I like to populate multiple select tag with different classname
<?php $count = 2; ?>
<div id="comments" hidden><?php echo htmlspecialchars($count); ?></div>
<?php for($i = 1; $i <= $count; $i++){ ?>
<input type="text" readonly="readonly" class="resone<?php echo $i; ?>" id="resone">
<select name="artist_1" class="part<?php echo $i; ?>" id="part">
<option value="" disabled selected>Select Category</option>
<option value="1">medicine</option>
<option value="2">shoes</option>
</select>
<?php }?>
jquery. I like to put the onchange function into the loop to manipulate the target class value
<script>
$(function() {
var count = document.getElementById("comments").textContent;
for (var i = 1; i <= count; i++) {
$('.part' + i).change(function() {
var display = $('.part' + i).find(":selected").val();
$('.resone' + i).val(display);
})
}
})
</script>
I hope you could help me with this one.

You are overcomplicating things and abusing the class by adding a counter to it.
Here is my suggestion - you can actually ignore the IDs and the script does not care about the count, just about how many ".part" there are
$(function() {
$(".part").on("change", function() {
$(this).prev(".resone").val(this.value);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" readonly="readonly" class="resone" id="resone0">
<select name="artist_1" class="part" id="part0">
<option value="" disabled selected>Select Category</option>
<option value="1">medicine</option>
<option value="2">shoes</option>
</select>
<hr/>
<input type="text" readonly="readonly" class="resone" id="resone1">
<select name="artist_1" class="part" id="part1">
<option value="" disabled selected>Select Category</option>
<option value="1">medicine</option>
<option value="2">shoes</option>
</select>
PHP: - the IDs are not even used
<?php for($i = 1; $i <= $count; $i++){ ?>
<input type="text" readonly="readonly" class="resone" id="resone<?php echo $i; ?>">
<select name="artist_1" class="part" id="part<?php echo $i; ?>">
<option value="" disabled selected>Select Category</option>
<option value="1">medicine</option>
<option value="2">shoes</option>
</select>
<?php }?>

You don't need to use a for loop, just give the select a common class and do like this:
$(function() {
$('.part').change(function() {
var display = $(this).val();
$(this).next('.resone').val(display);
})
})
Since I can't see the element with the class resone i can't make sure if $(this).next('.resone').val(display) works.
Code example
$(function() {
$('.part').change(function() {
var display = $(this).val();
$(this).next('.resone').val(display);
})
})
<?php $count = 2; ?>
<div id="comments" hidden>
<?php echo htmlspecialchars($count); ?>
</div>
<?php for($i = 1; $i <= $count; $i++){ ?>
<select name="artist_1" class="part" >
<option value="" disabled selected>Select Category</option>
<option value="1">medicine</option>
<option value="2">shoes</option>
</select>
<?php }?>

Related

HTML get value of select popoulated by PHP array

I have a view that that I have written in HTML and PHP that is like the following:
<select name="category" id="_category" class="_cateogry" onchange="submitTheForm() >
option value="">Please select</option>
<?php foreach ($categories as $contents ) {?>
<option value="<?php echo $contents->id;?>" selected="selected"><?php echo $contents->name;?></option>
<?php }?>
</select>
Now, I want to get <?php echo $contents->name;?> when the onChange function is called.
I tried to resolve it unsuccessfully in JS, and here is the JS code that I attempted:
function submitTheForm () {
var selectElement = document.getElementById('_category');
var selected = selectedElem.options[selectedElem.selectedIndex];
console.log(selected.text);
}
I want to console.log the selected <?php echo $contents->name;?> when the onchange function is called.
There is a missing " after the javascript function and your code could be modified a little like this - to use event rather than rely upon names or ids
<select name="category" id="_category" class="_cateogry" onchange="submitTheForm(event)" >
<option value="">Please select</option>
<?php foreach ($categories as $contents ) {?>
<option value="<?php echo $contents->id;?>" selected="selected"><?php echo $contents->name;?></option>
<?php }?>
</select>
function submitTheForm( event ) {
var value=event.target.value;
var text=event.target.options[event.target.options.selectedIndex].text;
console.log('%s -> %s',value,text);
}
<select name="category" id="_category" class="_cateogry" onChange="submitTheForm(this);" >
<option value="">Please select</option>
<option value="1">First</option>
<option value="2">Second</option>
</select>
<script>
function submitTheForm(sel)
{
console.log(sel.options[sel.selectedIndex].text);
}
</script>
You can do as per below
// select box code whch one you have alredy
<select name="category" id="_category" class="_cateogry" onChange="submitTheForm(this);" >
<option value="">Please select</option>
<?php foreach ($categories as $contents ) {?>
<option value="<?php echo $contents->id;?>" selected="selected"><?php echo $contents->name;?></option>
<?php }?>
</select>
//Javascript code to get selected options text value
<script>
function submitTheForm(sel)
{
console.log(sel.options[sel.selectedIndex].text);
}
</script>
Use the function addEventListener to bind the event change.
This is an alternative.
You can get the value and text using the context this.
document.getElementById('_category').addEventListener('change', function() {
console.log(this.value);
console.log(this.options[this.selectedIndex].text);
});
<select name="category" id="_category" class="_cateogry">
<option value="">Please select</option>
<option value="1595">Ele</option>
</select>
You can use jquery easily rather than javascript:
function submitTheForm () {
var optionName = jQuery('#_category option:selected').text();
alert(optionName);
}

check one of the select box is selected

i have 4 selectbox ,first one is vehicle selectbox and other three are sub of that vehicle select box ,if i select vehicle select box and click button i want to show a error message ,because one of the sub select is also i want to selected .... any one help ..i am just beginner in jquery/javascript
in simplest words :p ..check one of the sub select box(cars , caravans,buses select box) is selected if i selected main vehicle selectbox...
my code :
<div class="members-wrap-vehicle">
<label>Vehicle</label>
<select name="reservation[vehicle]">
<option value="0">Select</option>
<?php for($i=1;$i<11;$i++) { ?>
<option <?php if($_POST['reservation']['vehicle'] == $i) { echo 'selected="selected"'; }?> value="<?php echo $i;?>"><?php echo $i;?></option>
<?php } ?>
</select>
</div>
<div class="members-vehicle-list" <?php if($_POST['reservation']['vehicle'] == 0) { echo 'style="display: none;"'; } ?> >
<div class="members-wrap-adult">
<label>Cars</label>
<select name="reservation[cars]">
<option value="0">Select</option>
<?php for($i=1;$i<11;$i++) { ?>
<option <?php if($_POST['reservation']['cars'] == $i) { echo 'selected="selected"'; }?> value="<?php echo $i;?>"><?php echo $i;?></option>
<?php } ?>
</select>
</div>
<div class="members-wrap-child">
<label>Caravans</label>
<select name="reservation[caravans]">
<option value="0">Select</option>
<?php for($i=1;$i<11;$i++) { ?>
<option <?php if($_POST['reservation']['caravans'] == $i) { echo 'selected="selected"'; }?> value="<?php echo $i;?>"><?php echo $i;?></option>
<?php } ?>
</select>
</div>
<div class="members-wrap-infant">
<label>Buses</label>
<select name="reservation[buses]">
<option value="0">Select</option>
<?php for($i=1;$i<5;$i++) { ?>
<option <?php if($_POST['reservation']['buses'] == $i) { echo 'selected="selected"'; }?> value="<?php echo $i;?>"><?php echo $i;?> </option>
<?php } ?>
</select>
</div>
Take a look at this SO question: How to check if an option is selected?
Using what is suggested in that link, add an alert with whatever message you want if no option has been selected.
There are new lines of code but have certain changes for better understanding for you and test.
HTML code
<div class="members-wrap-vehicle">
<label>Vehicle</label>
<select name="reservation[vehicle]">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="members-vehicle-list">
<div class="members-wrap-adult">
<label>Cars</label>
<select name="reservation[cars]">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="members-wrap-child">
<label>Caravans</label>
<select name="reservation[caravans]">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="members-wrap-infant">
<label>Buses</label>
<select name="reservation[buses]">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
jQuery Code
$(function(){
$('.members-wrap-vehicle select').change(function(){
var cars = $('.members-wrap-adult select option:selected').val();
var caravans = $('.members-wrap-child select option:selected').val();
var buses = $('.members-wrap-infant select option:selected').val();
if ( cars == 0 || caravans == 0 || buses == 0 ){
alert('please select any of cars or caravans or buses');
}
});
});
Hope this works for you. THank YOu
This should work but there are some caveats. You have to change your <select> element names to ids (id = 'xxx'). Also, this function assumes that the number of vehicles in the sub menus totals the number in the vehicles menu. Please let me know if you need anything further! Cheers
$('#BUTTON_ID').on('click', function() {
var vehicle = $('#reservation[vehicle]').val();
var cars = $('#reservation[cars]').val();
var caravans = $('#reservation[caravans]').val();
var buses = $('#reservation[buses]').val();
if (vehicle == (cars + caravans + buses)) {
//do something
} else {
//error message
alert('Error has occurred.');
};
});

change drop down value on slection of other drop down

Need experts opinion on below mentioned code, i am not good with javascript. please help
what i need is,i have 2 drop downs. one is catid1 and 2nd is catid ...
catid loads some values from databases, and catid1 have some manual entries, few of them are same and few are different. but i want is when i will select catid1 value from list like "abc" then catid value should be changed to same as catid1 "abc"
i have tried some different ways but can't resolve this, any one please suggest either this could be possible or not.
<div class="col-md-4">
<div class="form-group">
<label for="catId"><?php echo $categoryField; ?></label>
<select class="form-control" name="catId1" id="catId1" onChange="qt();">
<option> Select Base Query Type </option>
</select>
<span class="help-block"><?php echo $categoryHelp; ?></span>
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="catId"><?php echo $categoryField; ?></label>
<select class="form-control" name="catId" id="catId">
<?php
$tcat = "SELECT catId, catName FROM categories WHERE userId = ".$userId." AND isActive = 1 ";
$rest = mysqli_query($mysqli, $tcat) or die('-2'.mysqli_error());
?>
<option value="..."><?php echo $selectOption; ?></option>
<?php while ($tcatrow = mysqli_fetch_assoc($rest)) { ?>
<option value="<?php echo $tcatrow['catId']; ?>"><?php echo clean($tcatrow['catName']); ?></option>
<?php } ?>
</select>
<span class="help-block"><?php echo $categoryHelp; ?></span>
</div>
</div>
</div>
sample code which i have tried is as below as well but it's not working in my case.
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
var selects = document.querySelectorAll('select[name="dropdown[]"]');
selects[0].addEventListener('change', function () {
for (var i = 0; i < selects.length; i++) {
selects[i].value = selects[0].value;
}
});
You forgot your script tags in the second example:
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
<select name="dropdown[]">
<option value="1">Sony</option>
<option value="2">Nintendo</option>
<option value="3">Microsoft</option>
</select>
<script language="javascript">
var selects = document.querySelectorAll('select[name="dropdown[]"]');
selects[0].addEventListener('change', function () {
for (var i = 0; i < selects.length; i++) {
selects[i].value = selects[0].value;
}
});
</script>
jsfiddle: https://jsfiddle.net/ge127u8d/
Yes you can do it by javascript or Jquery. Its easier in Jquery like
function qt() {
var catId1Val = $('#catId1 :selected').val();
$("#catId> option").each(function() {
if (this.value == catId1Val)
$("#catId select").val(this.value);
});
}
Check out the following jQuery method:
http://api.jquery.com/val/
http://api.jquery.com/each/
http://jsfiddle.net/Rx3AP/

Multiple Options/MYSQL Records to input box

I wondered if anyone would be able to help me with this as I just can't for the life of me, get it to work.
any help would be most appreciated.
Thanks in advance
$('#options').change(function () {
var optionname=$(this).find('option:selected').attr('data-value');
var optionprice=$(this).find('option:selected').attr('data-price');
$('#optionname').val(optionname);
$('#optionprice').val(optionprice);
});
<select name="options[]" id="options" class="form-control" required>
<option value="">Select Option</option>
<?php
$results99 = $mysqli->query("SELECT * FROM productoptions WHERE productid = '$prod_id' AND cat = 1");
while($rows99 = $results99->fetch_assoc()) {
?>
<option data-value="<?php echo $rows99['optionname']; ?>" data-price="<?php echo $rows99['price']; ?>"><?php echo ucwords(strtolower($rows99['optionname'])); ?> (+<?php echo $rows99['price']; ?>)</option>
<?php
//$results99->free();
}
?>
</select>
<?php } ?>
<input type="text" name="optionname" id="optionname" />
<input type="text" name="optionprice" id="optionprice" />
I just can't get it to work properly

display a textbox if user select "Other" on the drop down menu retrieved from the database

pls help me with this one. I can't display the textbox if the user selects "Other" option in the drop down menu. the values in the drop down came from the database. thanks! :)
<th align="left" height="26" colspan="3"><strong>Return Reason Codes:</strong><span class="select">
<?php
echo "<select description='returnreason' type='text' id='returnreason' onchange=' showfield(this.options[this.selectedIndex].value)'>";
echo '<option id="0">'.' --Select Return Reason-- '.'</option>';
$sql = mysql_query("SELECT * FROM preturnreason");
while($record = mysql_fetch_assoc($sql))
{
echo '<option value=" '.$record['DESCRIPTION'].'">'.$record['DESCRIPTION']. '</option>';
}
echo '</select>';
?> <div id="div1"></div></th>
</tr>
and here's my javascript:
<script type="text/javascript">
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='Other: <input type="text" name="other" />';
else document.getElementById('div1').innerHTML='';
}
</script>
var input = document.createElement('input');
input.type = "text";
div1.appendChild(input);
stackoverflow. LINK
How do I add textboxes dynamically in Javascript?
Your Code :
<?php $sql = mysql_query("SELECT * FROM preturnreason");?>
<th align="left" height="26" colspan="3"><strong>Return Reason Codes:</strong><span class="select">
<select description='returnreason' id='returnreason' >
<option value="999">--Select Return Reason--</option>';
<?php
while($record = mysql_fetch_assoc($sql))
{ ?>
<option value="<?php echo $record['DESCRIPTION'] ?>"> <?php echo $record['DESCRIPTION'] ?> </option>
<?php } ?>
<option value="0">Other</option>';
</select>
?> <div id="myTxt"></div></th>
</tr>
Below is my sample code which gives demo to display a text-box if user select “Other” on the drop down menu.
HTML
<select id='sBox' onselect='chkOption()'>
<option value='9'>Select</option>
<option value='0'>Other</option>
<option value='1'>One</option>
</select>
<div id='myTxt' style="display: none">
<input type='text'>
</div>
JQuery
$('select').on('change', function() {
if( this.value == '0')
$("#myTxt").show();
else
$("#myTxt").hide();
})
Live Demo
(Answer based on A.P.'s answer)
If you'd rather use pure JS (no Jquery) you can use the following code:
<select id='sBox' onChange='checkchange()'>
<option value='9'>Select</option>
<option value='0'>Other</option>
<option value='1'>One</option>
</select>
<div id='myTxt' style="display: none">
<input type='text'>
</div>
and Javascript:
function checkchange() {
if(document.getElementById('sBox').value == '0') {
document.getElementById('myTxt').style.display='block';
}
else {
document.getElementById('myTxt').style.display='none';
}
};
Jsfiddle: here
Combining that to your code:
<th align="left" height="26" colspan="3"><strong>Return Reason Codes:</strong><span class="select">
<select description='returnreason' id='returnreason' onchange=' checkchange()'>
<option id="0"> --Select Return Reason-- </option>
<?php
$sql = mysql_query("SELECT * FROM preturnreason");
while($record = mysql_fetch_assoc($sql)) {
echo '<option value=" '.$record['DESCRIPTION'].'">'.$record['DESCRIPTION']. '</option>';
}
?>
<option value='other'>Other - please specify</option>
</select>
<div id="div1"><input type='text'></div></th>
</tr>
<script>
function checkchange() {
if(document.getElementById('returnreason').value == 'other') {
document.getElementById('div1').style.display='block';
}
else {
document.getElementById('div1').style.display='none';
}
}
</script>

Categories