HTML get value of select popoulated by PHP array - javascript

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

Related

Dependent Dropdown is not loading on selection of first dropdown

I have two dropdown. I am using Jquery to load second dropdown. without jqyery My php code is working fine. but when I use with jquery second dropdown becomes empty on selection of first drop down.
First Dropdown ( Education )
$sqleducation = "select * from education order by education_id asc ";
$reseducation = mysqli_query($conn,$sqleducation);
<select name="education" id="education">
<option value="-1">Please Select</option>
<?php while($roweducation=mysqli_fetch_array($reseducation)){ ?>
<option value="<?php echo $roweducation['education_id']?>">
<?php echo $roweducation['education_name']?>
</option>
<?php }?>
</select>
Second Drop Down ( Degree)
<select name="degree" id="degree" >
<option value="-1">Please Select</option>
<?php if(isset($_POST["education_id"]) && !empty($_POST["education_id"])){
$sqldegree = "SELECT * FROM degree WHERE education_id = ".$_POST['education_id']." ";
$resdegree = mysqli_query($conn,$sqldegree);
while($rowdegree=mysqli_fetch_array($resdegree))
{ ?>
<option value="<?php echo $rowdegree['degree_id']?>">
<?php echo $rowdegree['degree_name']?>
</option>
<?php } }?>
</select>
Second dropdown is using juery to load on selection of first dropdown Education.
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#education').on('change',function(){
var educationID = $(this).val();
if(educationID){
$.ajax({
type:'POST',
url:'education-career.php',
data:'education_id='+educationID,
success:function(html){
$('#degree').html(html);
}
});
}else{
$('#degree').html('<option value="">Select Education first</option>');
}
});});</script>
Try change below line
data:'education_id='+educationID,
to
data:{education_id : educationID},
Try this.(second select tag have to place in first page in order to use $('#degree').html(...))
First Dropdown
$sqleducation = "select * from education order by education_id asc ";
$reseducation = mysqli_query($conn,$sqleducation);
<select name="education" id="education">
<option value="-1">Please Select</option>
<?php while($roweducation=mysqli_fetch_array($reseducation)){ ?>
<option value="<?php echo $roweducation['education_id']?>">
<?php echo $roweducation['education_name']?>
</option>
<?php }?>
</select>
<select name="degree" id="degree" >
<option value="-1">Please Select</option>
</select>
Second Dropdown
<option value="-1">Please Select</option>
<?php if(isset($_POST["education_id"]) && !empty($_POST["education_id"])){
$sqldegree = "SELECT * FROM degree WHERE education_id = ".$_POST['education_id']." ";
$resdegree = mysqli_query($conn,$sqldegree);
while($rowdegree=mysqli_fetch_array($resdegree))
{ ?>
<option value="<?php echo $rowdegree['degree_id']?>">
<?php echo $rowdegree['degree_name']?>
</option>
<?php } }?>
Here in ajax, you are using the
data:'education_id='+educationID,
Which is used to post the data. and the variable name will be here education_id.
And in your second page you are trying to get:
isset($_POST["education"])
this only. So on second page you have to replace education with education_id.
change:
$('#education').on('change',function(){
To:
$('select#education').change(function(){

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.');
};
});

How to sum the select box value inside loop in jquery in php

Here is my html, I need to sum the value of select fields on change
<for i=0;i<3,i++) {
<select id="options_<?php echo $i ?>">
<option value="25">RS 25</option>
<option value="30">Rs 30</option>
<option value="45">Rs 45</option>
<option value="95">Rs 95</option>
</select>
}
<p id=""sum_of_select> </p>
For example if i value is 2 means i want to sum the value selected in 2 select fields (45 is selected in select 1 and 95 selected in select 2 the output should be 140 ) . How to get in jquery
PHP is server-side. JS is client side. You can't use PHP to find the sum at runtime. Here is an example of how you can do this with jQuery-
<for i=0;i<3,i++) {
<select class="sum-selector" id="options_<?php echo $i ?>">
<option value="25">RS 25</option>
<option value="30">Rs 30</option>
<option value="45">Rs 45</option>
<option value="95">Rs 95</option>
</select>
}
<p id=""sum_of_select> </p>
<script>
$('.sum-selector').change(getSum);
function getSum() {
var sum = 0;
$('.sum-selector').each(function(select) {
if(select.value) {
sum += parseInt(select.value);
}
});
alert('sum is: ' + sum);
}
</script>
first off, I recommend before asking a question on here, make sure you debug and check before submitting a question.
What your code looks like:
for i=0;i<3,i++) {
<select id="options_<?php echo $i ?>">
<option value="25">RS 25</option>
<option value="30">Rs 30</option>
<option value="45">Rs 45</option>
<option value="95">Rs 95</option>
</select>
}
<p id=""sum_of_select> </p>
Now to be honest, your code is a bit confusing. But I'll see if I can sum up something for you.
What your code should look like:
<?php
// start the loop
for i=0;i<3,i++) {
?>
<select id="options_<?php echo $i ?>">
<option value="25">RS 25</option>
<option value="30">Rs 30</option>
<option value="45">Rs 45</option>
<option value="95">Rs 95</option>
</select>
<?php
} // end the loop
?>
<!-- here will go your summary -->
<p id="sum_of_select"></p>
<script>
// and to use your PHP variable in Jquery or Javascript:
var yourVarName = <?php echo $i; ?>;
</script>
NOTE: Your file must be a PHP file to do this, else this won't work.
Hoped this helped.

Calling a controller function using javascript onchange event in zend

I have an select dropdown list on my view
<?php $level = $this->escapeHtml($user->level); ?>
<?php if ($level == 1): ?>
<option value="1" selected="selected">Administrator</option>
<option value="2">Manager</option>
<option value="3">HR Staff</option>
<?php elseif ($level == 2): ?>
<option value="1" >Administrator</option>
<option value="2" selected="selected">Manager</option>
<option value="3">HR Staff</option>
<?php elseif ($level == 3): ?>
<option value="1" >Administrator</option>
<option value="2" >Manager</option>
<option value="3" selected="selected">HR Staff</option>
<?php endif; ?>
</select>
and it has an onchange event that calls this javascript function
<script type='text/javascript'>
function changeLevel(obj){
}
</script>
and on my controller i have this function
public function editLevel()
{
> updating level code here.
}
What i want is every onchange in my view, i will call my editLevel function in my controller. how can i call a controller function using a javascript onchange? thanks in advance!

Form submits <select> as undefined

I have the following <select> inside a <form> that is submitted with ajax. The select is submitting with a value of: Undefined. What is wrong?
<select class="form-control" name="site_theme" id="site_theme" value="<?php $result = mysqli_query($con,"SELECT * FROM settings"); while($row = mysqli_fetch_array($result)) { echo $row['site_theme']; }?>">
<?php
$result = mysqli_query($con,"SELECT * FROM themes");
while($row = mysqli_fetch_array($result))
{
echo "<option VALUE='".$row['theme_name']."'>".$row['theme_name']."</option>";
}
?>
</select>
The javascript copied here to ugly to post so I made a jsFiddle here: http://jsfiddle.net/yz5r4/
Also the above code results as:
<select class="form-control" name="site_theme" id="site_theme" value="Amelia">
<option value="Amelia">Amelia</option>
<option value="Cerulean">Cerulean</option>
<option value="Cosmo">Cosmo</option>
<option value="Cyborg">Cyborg</option>
<option value="Flatly">Flatly</option>
<option value="Journal">Journal</option>
<option value="Readable">Readable</option>
<option value="Simplex">Simplex</option>
<option value="Slate">Slate</option>
<option value="Spacelab">Spacelab</option>
<option value="United">United</option>
</select>
you problems was first a return before ajax call.
second wrong selector for select!
Here is a sample that shows you. http://jsfiddle.net/yz5r4/3/
your selector : $('input$("#site_theme")')
but it should be $("#site_theme") or $("select#site_theme")
HTML:
<select class="form-control" name="site_theme" id="site_theme" value="Amelia">
<option value="Amelia">Amelia</option>
<option value="Cerulean">Cerulean</option>
<option value="Cosmo">Cosmo</option>
<option value="Cyborg">Cyborg</option>
<option value="Flatly">Flatly</option>
<option value="Journal">Journal</option>
<option value="Readable">Readable</option>
<option value="Simplex">Simplex</option>
<option value="Slate">Slate</option>
<option value="Spacelab">Spacelab</option>
<option value="United">United</option>
</select>
<input type="button" id="mclick" value="click" />
JS:
// General Form Submit
$(function () {
$('.error').hide();
$("#mclick").click(function () {
// validate and process form here
var theme = $("#site_theme").val();
alert(theme);
});
});

Categories