I need to implement this js in order to fill in different fields on change event of a select field.
<select class="form-control" name='brands_list'>
<option value="0">Seleziona il produttore</option>
<?php
while ($listabrand=mysqli_fetch_array($brands)){
echo '<option value="'.$listabrand[0].','.$listabrand[1].','.$listabrand[2].'">'.$listabrand['0'].' - '.$listabrand['1'].'</option>';
}?>
</select>
This is the js to implement. I should add a second action that fill in the input field named 'brand_link' assuming the array value [2]:
<script>
$('select[name="brands_list"]').change(function(){
$('input[name="brand_name"]').val($('select[name="brands_list"] option:selected').text().split(' - ')[1]);
});
</script>
I made several attempts but without results such as
<script>
$('select[name="brands_list"]').change(function(){
$('input[name="brand_name"]').val($('select[name="brands_list"] option:selected').text().split(' - ')[1]);
});
$('select[name="brands_list"]').change(function(){
$('input[name="brand_link"]').val($('select[name="brands_list"] option:selected').text()[2]);
});
Any help?
You can do it all within the one function. The reason your pastebin didn't work is because 1) you aren't operating on the .val() of the selected item (rather the element itself) and 2) you didn't split the value by comma, like you split the .text() by hyphen.
$('select[name="brands_list"]').change(function(){
var $selectedOption = $('select[name="brands_list"] option:selected');
$('input[name="brand_name"]').val($selectedOption.text().split(' - ')[1]);
$('input[name="brand_link"]').val($selectedOption.val().split(',')[2]);
});
$(".form-control").change(function()
{
//alert( this.value );
var sl_value = this.value;
$('input[name="brand_name"]').val(sl_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="brand_name" value="">
<?php $listabrand=mysqli_fetch_array($brands);?>
<select class="form-control" name='brands_list'>
<option value="Seleziona il produttore">Seleziona il produttore</option>
<?php
foreach($listabrand as $brand){ ?>
<option value="<?php echo $brand;?>"><?php echo $brand;?></option>
<?php } ?>
</select>
in first step, get dropdown selected value in jquery on change. And save this value in jQuery variable. And then insert this value in textbox using jQuery. Thanks
Related
I have a question.
I want to achieve something, however, I have never done this so unfortunately I do not know how to handle this.
In my screen I fill a dropdown box with names from a sql db.
Now I would like, as soon as a name is chosen from that dropdown that the other data be loaded such as, for example, min and max values.
I would like to use these values to, for example, be able to give limits to input fields.
So as soon as an entry field falls outside of the loaded values, the entry field then turns red.
However, I would like to use this without the submit button of the form being pressed.
Is this possible ? if so can someone help me with this?
The code i use to fill my selectbox is this.:
<td>
<div class="controls">
<select name="prod" id="employee" onclick="updateBottomValue(this.value);" onchange="mys1()" style="width: 245px;">
<option value="" disabled selected="selected[]" multiple="multiple">Selecteer Product</option>
<?php
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM specsv1 where RActive = 'y' order by RNaam";
$q = $pdo->prepare($sql);
$q->execute(array($Id,$RNaam));
Database::disconnect();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['Id'] . "'>" . $row['RNaam'] . "</option>";
}
?>
</select>
<?php if (!empty($ProductError)): ?>
<span class="help-inline"><?php echo $ProductError;?></span>
<?php endif; ?>
</div>
<span id="selectedValue"></span>
<input STYLE="width: 6em" name="rrss" type="text" id='rrss'>
</td>
The code i have to get the selected name is this.:
<script>
function updateBottomValue(selectedvalue) {
document.getElementById("selectedValue").innerHTML=selectedvalue;
document.getElementById('rrss').value = selectedvalue;
}
</script>
Yap it is possible.
And maybe this example ajax for what you want, feel free to modify to fit your requirements.
function viewMinMax(value){
if (value == 'a'){
tempurl = "https://api.myjson.com/bins/dv40y";
}else if (value == 'b'){
tempurl = "https://api.myjson.com/bins/egjmq";
}
$.ajax({
url: tempurl,
type: "get",
dataType: "JSON",
data: {}, //this is data you send to your server
success: function(res)
{
$('#info').show();
document.getElementById("info").innerHTML = 'Your min value: ' + res.min + ', Your max value: ' + res.max;
$('#min').val(res.min);
$('#max').val(res.max);
}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<select name="product_select" id="product_select" onchange="viewMinMax(this.value)">
<option value="">Select Product</option>
<option value="a">Product A</option>
<option value="b">Product B</option>
</select>
<p id="info" style="display:none;"></p>
<h3>Load the min & Max</h3>
<label for="min">Min</label>
<input type="text" name="min" id="min" value="">
<br>
<label for="max">Max</label>
<input type="text" name="max" id="max" value="">
</form>
ignore the tempurl it can be change with your action to select data based on value to your DB.
Is it possible? Absolutely. There are a few ways of going about it. One easy way is to use jQuery to fire off what's called an AJAX call as soon as the dropdown value changes. The AJAX call your PHP script and get back some HTML that it will place wherever you want it on the screen.
It's a big subject, so difficult to give you exact answers, but google jquery ajax dropdown onchange and you should be able to get enough information to get you going. One of them is the following (there are many):
jQuery Load form elements through ajax, from onchange event of drop down box
I am using PHP to dynamically populate a select box (a list of equipment). The value is set with the ID of the item selected so I can use it later in my programming.
What I need help with...
Based on the item selected I need to show/hide one of two form fields but I can't use the value as this is the id.
What I need to be able to do is read the text in the select box which will contain the item name with either (Service: Set by dates) or (Service: Set by hours) and show either the form field for the date or the form field for the hours?
Is this possible? I can find loads great resources based on the value but not on the text in the select.
I think something like this should work but not sure how to use the text in the select rather than the value.
$(function() {
$('#system').change(function(){
$('.system').hide();
$('#' + $(this).val()).show();
});
});
Any help would be greatly appreciated!!!!
Regards
Matt
(N.B this is what I'm working with at the mo based on the answers so far, thank you all so much for the help (and for your example Louys Patrice Bessette) - not quite there yet... I was getting an error and managed to track it back to the script not getting the result from the select box. See below now working code! Thanks all!!!
<div class="col">
<div class="form-group">
<label for="system_select">Equipment or System to be serviced</label>
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name; ?></option> <?php
}
?>
</select>
</div>
</div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
$("#due_dates").hide(); // Hide both divs
$("#due_hours").hide(); // Hide both divs
$('#system_select').change(function(){
var dataType = $(this).find(':selected').attr('data-type') // should be "Set by dates" or "Set by hours"
if (dataType == 'Set by dates') {
$("#due_hours").hide();
$("#due_dates").show();
} else if (dataType == 'Set by hours') {
$("#due_dates").hide();
$("#due_hours").show();
}
});
});
</script>
<div class="row">
<div class="col-md-3" id="due_date">
<div class="form-group">
<label for="service_date">Next Service (Set by dates)</label>
<input type="date" class="form-control" name="service_date" id="service_date" value="<?php echo escape(Input::get('service_date')); ?>" autocomplete="off">
</div>
</div>
<div class="col-md-3" id="due_hour">
<div class="form-group">
<label for="service_hours">Next Service (Set by hours)</label>
<input type="number" class="form-control" name="service_hours" id="service_hours" value="<?php echo escape(Input::get('service_hours')); ?>" autocomplete="off">
</div>
</div>
</div>
I think that you PHP $system->service_type; is echoing either "Set by dates" or "Set by hours".
If you echo that in a data attribute like this:
<select class="form-control" name="system_select" id="system_select">
<option></option>
<?php
$systems = DB::getInstance()->get('ym_system', 'vessel_id', '=', $vid);
foreach ($systems->results() as $system) {
?><option data-type="<?php echo $system->service_type; ?>" value="<?php echo $system->system_id ?>"><?php echo $system->system_name . ' (Service: '. $system->service_type .')'; ?></option> <?php
}
?>
</select>
Then, in jQuery, you could use it like this to decide to show <div id="due_hours" class="col-md-3"> or <div id="due_hours" class="col-md-3">.
$(function() {
$('#system').change(function(){
$('.system').hide(); // I don't know what this is for...
$("div[id=^'due']").hide(); // Hide both divs
var dataType = $(this).data("type"); // should be "Set by dates" or "Set by hours"
var type = dataType.split(" by ")[1]; // should be "dates" ot "hours"
$("#due_"+type).show();
});
});
Now be carefull with the s on dates...
Try this out... Console.log the values to make sure you have the correct one to match the id to show.
;)
If $(".classname").text() is not working you could try to add that info that you need in a "data" attribute.
Something like this ->
<option data-service="service name" class="myClass">15</option>
Using data attributes can give you a lot of freedom on what you can add. You could add lots of information that a normal user cant read (without inspecting element).
Then you would simply do something like this ->
$(".myClass").on("click", function() {
var serviceData = $(this).attr("data-service");
})
You can then do if checks, compare and whatever you need.
EDIT: Or you can use your approach with on.change and get the selected data attr, it would probably be better
If you change your select into something like this:
<select class="form-control" name="system_select" id="system_select">
<option data-hide='#due_date' data-show='#due_hours'>Show Hours</option>
<option data-hide='#due_hours' data-show='#due_date' value="B">Show Dates</option>
</select>
And your jquery like this:
$('#system_select').change(function () {
$($(this).children("option:selected").attr("data-hide")).hide();
$($(this).children("option:selected").attr("data-show")).show();
});
It could work.
It appears that I am facing a common beginer's problem but I haven't managed to solved it on my code.
What I want to do:
I have created a database and I am currently working on a simple UI for updating it. So, I use
One drop-down menu populated by a mySQL table
Some forms with their values changed accordingly to the drop down selection.
Code(Simplified a little):
<html>
<body>
<form method="post">
<select class="dropdown" id="dropdown_id" onChange='fillFun(this.value)' >
<option disabled selected value style="display:none"> -- select an option -- </option>
<?php
//stuff pdo connection
$pdo = new PDO("mysql:host=$servername;dbname=myDatabase", $user, $password);
try
{
$result = $pdo->query("SELECT * FROM dbTable");
foreach($result as $row)
{
echo '<option value="'.$row.'"';
echo '>'. $row['last_name'].' '. $row['first_name'].'</option>'."\n";
}
}
catch(PDOException $e) { echo 'No Results'; }
?>
</select >
</form>
<form id="forms" action="results.php" method="post">
Last Name: <input type="text" id="last_name" /><br><br>
First Name: <input type="text" id="first_name" /><br><br>
<input type="submit" />
</form>
<script>
function fillFun(fill)
{
document.getElementById('last_name').value = fill[1];
document.getElementById('first_name').value = fill[2];
}
</script>
<body>
Problem:
this.value = "Array"
After researching a little I found a couple of question with a similar problem.(For instace this one)
The thing is that I can't(or don't know how,to be precise) apply the given solution print_r() or var_dump() since I am echo-ing an option value. Another way to solve a similar problem was the use of json_encode() but after the change of
onChange='fillFun(this.value)'
with
onChange='fillFun(json_encode(this.value))'
the problem wasn't solved. On the contrary, it seems that now the fill parameter was null.(Nothing happens on change).
What am I missing here?Thanks.
Instead of referring to this.value you can pass the event object to fillFunc function and obtain the value through event.target.value.
So fillFunc will be updated to:
fillFunc(event) {
document.getElementById('last_name').value = event.target.value[1];
document.getElementById('first_name').value = event.target.value[2];
}
And pass event to your onchange handler.,
<select onchange="filFunc(event)"></select>
I have written a jquery code for the following purpose:
There is a list of Fields, and a list of sub-fields. When user clicks on a field, the relevant subfields would be shown. Both lists are multiple-enabled <select>.
HERE IS THE JS FIDDLE (exploring it with FF it works, yet with chrome fails)
http://jsfiddle.net/mostafatalebi/WUR7F/
I use the most recent versions of Chrome, Firefox, and IE8. This code works fine for Firefox but fails in the other two.
Here is the jquery code:
$(document).ready(function(){
$('select[name="branch[]"]').change(function () {
var $branch = $(this).children(':selected'),
$subbranch = $('[name="subbranch[]"]').children('option');
$subbranch.hide()
$branch.each(function () {
var branch = $(this).val();
$subbranch.each(function () {
if ($(this).attr("id") == "par"+branch) {
$(this).show();
}
});
});
}).change();
});
And here is the HTML (for Mother-Fields) which the jquery is applied to:
<option selected value="false">Please Select the Field:</option>
<?php
$db->where("parent", 1);
$db->where("type", 1); // means institute
$branches = $db->get("fields")->result_array();
$brancc = count($branches);
for($i=0; $i < $brancc; $i++)
{
?>
<option class='branch-item' value="<?php echo $branches[$i]['id']; ?>" >
<?php echo $branches[$i]['title']; ?></option>
<?php
}
?>
</select><br />
And here is the HTML (Child-Fields) to which jquery is applied:
<select multiple class="form-option-multiple" name="subbranch[]">
<?php
$db->where("parent", 0);
$db->where("type", 1); // means institute
$suboptions = $db->get("fields")->result_array();
$suboptionscc = count($suboptions);
for($i=0; $i < $suboptionscc; $i++) {
?>
<option class='subbranch-item' id='par<?php echo $suboptions[$i]['parent_id']; ?>'
value="<?php echo $suboptions[$i]['id']; ?>" ><?php echo $suboptions[$i]['title']; ?></option>
<?php
}
?>
</select>
<br />
Both lists are initially filled with the data retrieved from Database.
Two things:
dozens of your subbranch-options have the same DOM id. DOM ids are supposed to be unique in the document. I've changed your code to use a class instead: jsFiddle
if ($(this).hasClass("par"+branch)) {
The problem is that you are trying to hide options in a multiselect by setting display: none. Both Chrome and IE do not support that. You will have to add and remove options instead.
I've build a second fiddle that does that: jsFiddle
I added a third, invisible select that holds all your generated options. Whenever the user changes the branch, we clear the subbranch select and copy all the matching options from the hidden third into it.
Why do you have the two instances of .change() first of all?
Isn't that redundant? That could be resetting your on change event also.
Because this is the real issue... rather than:
$('select[name="branch[]"]').change(function() {})
For compatibility, you need to use:
$('select[name="branch[]"]').on('change', function() {})
Here is another problem. This code needs to be moved out the each() it is in:
var branch = $(this).val();
And because the selects are multi-selects, this code will not work:
if ($(this).attr("id") == "par"+branch) {
$(this).show();
}
Sometimes branch will be multiple values.
This works in Chrome: http://jsfiddle.net/digitalextremist/3rzLs/
Check that out to see extreme changes needed to solve all your problems:
$(document).ready(function(){
$('select[name="branch[]"]').on('change', function() {
var $branch = $(this).children(':selected'),
$subbranch = $('#suboptions').children('option');
$('[name="subbranch[]"]').empty()
var branch = $(this).val();
console.log( branch )
$branch.each(function () {
$subbranch.each(function () {
if ( branch.indexOf( $(this).attr("id").replace("par","") ) >= 0) {
$('[name="subbranch[]"]').append( $(this).clone() ).show();
}
});
});
}).change();
});
With HTML:
Selecting on any Box of Parents' item should show a list related to the parent in Box of Children
<label>Box of Parents</label>
<select id="branches" class="form-option-multiple" name="branch[]" multiple="">
<option selected="" value="false">لطفا زمینه فعالیت خود را انتخاب نمایید</option>
<option class="branch-item" value="14">
هنرهای دستی</option>
<option class="branch-item" value="15">
کامپیوتر</option>
...
</select>
<!-- Then here is the second Child --><br/>
<label>Box of Parents</label>
<select size="9" multiple="" class="form-option-multiple" name="subbranch[]">
</select>
<div id="suboptions" style="display: none">
<option style="display: none;" class="subbranch-item" id="par14" value="40">قالیبافی</option>
<option style="display: none;" class="subbranch-item" id="par14" value="48">نقاشی</option>
<option style="display: none;" class="subbranch-item" id="par14" value="49">گرافیک</option>
...
</div>
I have the following Drop Down List in php:
<select id="choice" name="choice" style="width: 121px">
<?php
foreach($xml->children() as $pizza){
?>
<option value="<?php echo $pizza; ?>" selected=""><?php echo $pizza; ?></option>
<?php }?>
</select><input TYPE = "button" id="addbt" Name = "addbt" VALUE = "Add Pizza">
and I am using the following Jquery:
<script type="text/javascript">
$("#addbt").click(function () {
$('#choice').clone().insertAfter("#choice");
});
</script>
I am trying to clone the Drop Down List which is attached to an xml file (I managed till here) and add the Jquery necessary so each new drop down list clone has a new id (a single number difference would be enough. Something like choices_00 then choices_01 and so on).
Since I am totally new to Jquery and php I am asking for any advice or help.
$("#addbt").click(function () {
$('#choice').clone()
.attr('id', 'newid')
.attr('name', 'newname')
.insertAfter("#choice");
});
To ensure you get a new name and id each time, consider adding a class name to the select so you can count how many exist.
HTML:
<select id="choice" name="choice" class="ddl" style="width: 121px">
<?php
foreach($xml->children() as $pizza){
?>
<option value="<?php echo $pizza; ?>" selected=""><?php echo $pizza; ?></option>
<?php }?>
</select>
JS:
$("#addbt").click(function () {
$('#choice').clone()
.attr('id', 'choice' + $('.ddl').length)
.attr('name', 'choice' + $('.ddl').length)
.insertAfter(".ddl:last");
});
Otherwise, track how many times the button has been clicked with a global variable (ugh) or data attribute.
I think you are after this: http://jsfiddle.net/ehQan/
$("#addbt").click(function () {
$('#choice').clone().attr( 'id', 'choices_' +$(this).index()).insertAfter("#choice");
});
You can change the id using the jQuery attr() method before you insert it:
<script type="text/javascript">
$("#addbt").click(function () {
$('#choice').clone().attr('id','Your new id').insertAfter("#choice");
});
</script>
With this code you can push the button as many times as you want:
<script type="text/javascript">
var times = 0;
$("#addbt").click(function () {
times++;
$('#choice').clone().attr( 'id', 'choices_' + times ).insertAfter("#choice");
});
</script>