JQuery/Javascript -- show div based on select but NOT value - javascript

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.

Related

jquery select multiple options show and hide input type number with placeholder

<div class="form-group"><label for="unit_of">Unit of Measure</label>
<select class="form-control-sm selectpicker" multiple="multiple" id="unit_of" name="unit_of[]" data-selected-text-format="count">
<?php $sql = "select * from unit_of";
$res = mysqli_query($db_handle, $sql);
while ($list = mysqli_fetch_assoc($res)) {
$unit_of = $list['unit_of'];
?>
<option><?= $unit_of; ?></option>
<?php
}
?>
</select>
</div>
<input type="text" class="form-control-sm" id="rates" name="rates" >
<input type="text" class="form-control-sm" id="rates1" name="rates1" style="display:none">
<input type="text" class="form-control-sm" id="rates2" name="rates2" style="display:none">
In the dropdown
Per Minute
Per Page,
Per Hour,
Per Day,
Per Month,
Per Item,
Per Contract,
Others
I want onchange multiple select hide and show input types number e.g.(name="per_page") e.g.("Enter Rate Per Page") for three input type
Thanks in Advance
If I understand correctly, there are 2 questions here really:
How to restrict a multiple select to a max of 3 selections?
There are multiple ways to achieve this, but my recommendation would be to validate this right before the form is submitted. If you're using a form validation library, try adding the code in there. If not, then you can add a custom submit event handler that will validate the selections. Maybe something like:
$("form").on("submit", function(e) {
var selectionCount = $("#unit_of option:selected").length;
if (selectionCount > 3) {
e.preventDefault();
alert("You may only select up to 3 options.");
}
});
How to add a placeholder to the multiple select?
You can add a placeholder option just before the PHP code adds the other options, like so:
<select class="form-control-sm selectpicker" multiple="multiple" id="unit_of"
name="unit_of[]" data-selected-text-format="count">
<option value="">Enter Rate Per Page</option>
<?php $sql = "select * from unit_of";
$res = mysqli_query($db_handle, $sql);
while ($list = mysqli_fetch_assoc($res)) {
$unit_of = $list['unit_of'];
?>
<option><?= $unit_of; ?></option>
<?php
}
?>
</select>
Of course, with this approach, you'll need to add extra validation code to make sure that the placeholder option is not one of the selected options.

Load sql data after making a choose out a select box?

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

Add second SELECT on change of first SELECT (PHP/AJAX) Not working as it should

firstly, let me express that I have tried four methods (All slightly different) that all seem to produce the same issue, which is no data being outputted, even simple echo 'test' to rule out a DB issue (and also trying TEST in html on the called page, no result.
Here is a snapshot of the HTML and Javascript:
(document).on('change','category_id',function(){
var id = $(this).val();
$.ajax({
method: 'POST',
url: 'supportgetsubcats.php',
data: {'subcatid' : id},
success: function(data){
$('#subcatresponse').hide().html(data).fadeIn(); // update the DIV
}
});
});
<div class="form-group">
<label class="col-sm-2 control-label">Category *</label>
<div class="col-sm-4">
<select class="form-control" class="category_id" name="category_id" id="category_id">
<option value="" selected="selected">-- Select --</option>
<?php
$query="select * from support_categories where hide = '0' or hide is NULL order by name ASC";
$rs=sqlsrv_query($conn,$query);
while($row=sqlsrv_fetch_array($rs))
{
extract($row);
?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php
}
?>
</select>
</div>
</div><!-- form-group -->
<div class="form-group">
<div id="subcatresponse" name="subcatresponse" class="col-sm-4">
</div>
</div><!-- form-group -->
Here is the PHP that is called:
<?php require_once("includes/header.php");
error_reporting(E_ALL);
echo 'TEST';
if(isset($_POST["subcatid"])){
// Capture selected country
$category = $_POST["subcatid"];
$query="select * from support_subcategories where parent_category = '" . $category . "' order by name ASC";
$rsp=sqlsrv_query($conn,$query);
$subCatArr = array();
while($row=sqlsrv_fetch_array($rsp))
{
$subcat = $row['name'];
array_push($subCatArr, $category, $subcat);
}
// Display city dropdown based on country name
if($category == '-- Select --'){
} else {
echo '<label class="col-sm-2 control-label">Sub Category</label>';
echo '<select class="form-control" name="subcategory_id" id="subcategory_id">';
foreach($subCatArr[$category] as $value){
echo '<option value="'. $value .'">'. $value .'</option>';
}
echo "</select>";
}
}
?>
I get no response, not even basic text back, so I am not entirely sure what is wrong with the AJAX call, jQuery is included and proven to be working as the menu system on this interface won't display without jQuery so I am confident that is not the issue.
It looks like for whatever reason, the data from the HTML Select is not being passed to the AJAX call for POST.
Any thoughts greatly appreciated, TIA.
Try changing
(document).on('change', 'category_id', function() {
to
$(document).on('change', '#category_id', function() {
The second parameter to the on call takes a selector, but you seem to be passing in the name of the element instead. The name of the element is used when trying to access the element in PHP, and you use the selector (id, class, element) in JavaScript.
Alternatively, you could also use
$('#category_id').on('change', function()
You haven't posted it in your question, but in case you don't have it, it is always a good idea to only execute your jQuery code after the page has finished loading, otherwise your code may be trying to access an element that hasn't been loaded yet.
Surround your jQuery code with
$(document).ready(function() {
// Run jQuery code
}
add type='POST' to your ajax call
Also change this
(document).on('change','category_id',function(){
to
$(document).on('change','category_id',function(){

Watching for when any element changes

I have a rather unique issue in jquery to solve. I have a div wrapper:
<div class="formWrapper"></div>
This contains a set of elements that should, when they change (doesn't matter which element changes) - should (for example) be stored in a data object, and that object logged to the console - for now.
So:
<div class="formWrapper">
<div class="floatRight">
<div>
<label>Select a Project Manager</label>
<select class="projectManager">
<?php foreach($projectManagers as $name){ ?>
<option><?php echo $name; ?></option>
<?php } ?>
</select>
</div>
<div>
<label>Select a Division</label>
<select class="division">
<?php foreach($divisions as $division){ ?>
<option><?php echo $division['division_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="floatLeft">
<div>
<label>Select a Client</label>
<select class="client">
<?php foreach($clients as $client){ ?>
<option><?php echo $client['client_company_name']; ?></option>
<?php } ?>
</select>
</div>
<div>
<label>Choose a Date</label>
<input type="text" class="date" placeholder="Click to choose a date"/>
</div>
</div>
</div>
Pretty simple to see whats going on. But what if projectManager changes or divison or ... both, or all the elements, a simple change() might work for one element but I need to watch all the element and dynamically update a data object such that each time an element changes, the console spits out a different data object.
The end goal
Have a data object, for example data = {pm : pm_selected_value} for if the user JUST selects pm and then, if they change division - the data object should update to should: data = {pm : pm_selected_value, divsion: division_selected_value} and so on ...
I know how to get the value of each element, I don't know how to create a dynamic data object like this while watching each element.
The catch, and I think change() from reading the docs does this, is that even if I have a data object like this:
data = {pm : pm_selected_value, divsion: division_selected_value}
and I go an update the pm (so selecting a different pm), the data object should instantly update to reflect that change:
data = {pm : pm_selected_NEW_value, divsion: division_selected_value}
Now I can apply .change() to each element - but is there no way to apply it to a div to say - "excuse me mr JavaScript - please watch all form elements inside here for change, k thanks."
What you are looking to do it listen for any select value to get changed within the <div class="formWrapper"></div> so you should target the <div> and attach the change event to child <select>s
var choices = new Object();
$('.formwrapper').on('change', 'select', function(){
choices[$(this).attr('name')] = $(this).val();
console.log(choices);
});
One thing you should do is provide a unique name="" for each <select> so that you know what you are dealing with inside of the anonymous function()

Inaccurate retrieval of values from an input fields using javascript referenced by inputs class names

I have created an input fields populated by ids that I will use later to make a query in my database via javascript. Using foreach loop, the fields were populated correctly by their respective ids. Using javascript I want to be able to access this ids, however, using the onclick function that is based on their class name, the values for the first and second input fields are the only fields that returns the correct id value and the rest input field values were taken from the second input field having the id value of 2 instead of returning the right id value. What is the wrong with this? How could I retrieve right id values from this input fields? Thanks a lot. Here is my code
View:
<?php
foreach($data_currencies as $row){
?>
<div class="row-fluid">
<div class="span2"><input type='checkbox' class="currency_check_box" id='chk' name='currency_id[]' value="<?php echo $row->id; ?>" /></div>
<div class="span4" style="text-color:black;"><?php echo anchor("currencies/edit_currency/$row->id/$tennant_id",$row->pretty_name);?></div>
<div class="span4" style="text-color:black;"><?php echo $row->currency_code;?></div>
<div class="btn-group span1" id="condition" data-toggle="buttons-radio" >
<?php if($row->status==1) { ?>
<input type="text" value="<?php echo $row->id; ?>" class="btn active first" id="enable"/>
<input type="text" value="<?php echo $row->id; ?>" class="btn passive" id="disable"/>
<?php }
else{ ?>
<input type="text" value="<?php echo $row->id; ?>" class="btn off" id="enable"/>
<input type="text" value="<?php echo $row->id; ?>" class="btn active on" id="disable"/>
<?php } ?>
</div>
</div>
</address>
<address>
<?php
}
?>
Javascript
<script type="text/javascript">
$(".first").click(function(){
alert($(".first").val());
});
$(".passive ").click(function(){
alert($(".passive").val());
});
$(".off").click(function(){
alert($(".off").val());
});
$(".on ").click(function(){
alert($(".on").val());
});
</script>
Output:
Clicking the input field with id value 1
Clicking the input field with id value 2
Clicking the remaining input fields gives the same outputs
The problem is that you need to use the this keyword in your js. Otherwise you will just be getting the element with the first occurence of that class. Also considering all of your input fields have the 'btn' class why don't you change your js to
$(".btn").click(function(){
//Use 'this' to get the value of the element you clicked on
alert($(this).val());
});
Note You are looping through your rows in your PHP code but each time giving the elements the same id (id="enable" and id="disabled"). This will cause multiple elements to have the same id, which will invalidate your HTML and could cause you problems later on.
Try this
$(".first").click(function(){
alert($(this).val());
});
$(".passive ").click(function(){
alert($(this).val());
});
$(".off").click(function(){
alert($(this).val());
});
$(".on ").click(function(){
alert($(this).val());
});

Categories