How can I display selected values together using jQuery? - javascript

I have some dropdown fields which trigger a popup that allows the user to enter a value. I want this value to appear in the button here:
<button type="button" id="moving_average_output" name="moving_average_output" class="btn-primary col-xl-12 form-control">Value should appear here</button>
I'm able to get the most recently selected value to appear in the <button>, but I can't get all three values to appear together. Here is the full source code:
$("#comparator_indicator").on('change', function() {
var comparator_value = $(this).val();
$("#moving_average_output").text(comparator_value);
});
$("#right_side_indicator_select-me").on('change', function() {
//alert($(this).val());
if ($(this).val() == 1) {
$("#myModal_first").modal('show');
}else if($(this).val() == 2) {
$('#simple_moving_average').val('');
$("#myModal_second").modal('show');
}
});
$("#movingaveragebutton").on('click', function(event) {
event.preventDefault();
simplemovingaverage = $("#simple_moving_average").val();
$("#moving_average_output").text(simplemovingaverage);
});
$("#exponentialbutton").on('click', function(event) {
event.preventDefault();
exponentialstring = $("#exponentialstring").val();
exponentialnumber = $("#exponentialnumber").val();
$("#moving_average_output").text(exponentialstring+','+exponentialnumber);
});
/* ----------------------right side -------------------------------------------*/
$("#left_indicator_side_select-me").on('change', function() {
//alert($(this).val());
if ($(this).val() == 1) {
$("#myModal_first").modal('show');
}else if($(this).val() == 2) {
$('#simple_moving_average').val('');
$("#myModal_second").modal('show');
}
});
$("#movingaveragebutton").on('click', function(event) {
event.preventDefault();
simplemovingaverage = $("#simple_moving_average").val();
$("#moving_average_output").text(simplemovingaverage);
});
$("#exponentialbutton").on('click', function(event) {
event.preventDefault();
exponentialstring = $("#exponentialstring").val();
exponentialnumber = $("#exponentialnumber").val();
$("#moving_average_output").text(exponentialstring+','+exponentialnumber);
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="row block-9">
<div class="col-md-4 pr-md-4">
<div class="form-group">
<label for="sel1">Right Side Indicator:</label>
<select class="form-control" id="right_side_indicator_select-me" name="right_side_indicator_select-me">
<option>Select</option>
<option value="1">Moving Average</option>
<option value="2">Exponential Moving Average</option>
</select>
</div>
</div>
<div class="col-md-4 pr-md-4">
<div class="form-group">
<label for="sel1">Comparator:</label>
<select class="form-control" id="comparator_indicator" name="comparator_indicator">
<option>Select</option>
<option value="=">=</option>
<option value=">">></option>
<option value="<"><</option>
</select>
</div>
</div>
<div class="col-md-4 pr-md-4">
<div class="form-group">
<label for="sel1">Left Side Indicator:</label>
<select class="form-control" id="left_indicator_side_select-me" name="left_indicator_side_select-me">
<option>Select</option>
<option value="1">Moving Average</option>
<option value="2">Exponential Moving Average</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label for="sel1">Selected values</label>
<button type="button" id="moving_average_output" name="moving_average_output" class="btn-primary col-xl-12 form-control">value will display here</button>
</div>
<div class="form-group">
<div id="myModal_first" class="modal fade" role="dialog">
<div class="modal-dialog">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="modal-content">
<div class="modal-body">
<input type="text" name="simple_moving_average" id="simple_moving_average" class="form-control" placeholder="TEXT">
</div>
<button type="button" id="movingaveragebutton" name="movingaveragebutton" class="btn btn-primary col-xl-6 text-center" style="align-self: center !important;" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
<div class="form-group">
<div id="myModal_second" class="modal fade" role="dialog">
<div class="modal-dialog">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="modal-content">
<div class="modal-body">
<div class="row block-9">
<div class="col-md-6 pr-md-6">
<div class="form-group">
<select class="form-control" id="exponentialstring" name="exponentialstring">
<option>SELECT THE OPTIONS</option>
<option value="open">OPEN</option>
<option value="close">CLOSE</option>
<option value="low">LOW</option>
<option value="high">HIGH</option>
</select>
</div>
</div>
<div class="col-md-6 pr-md-6">
<div class="form-group">
<select class="form-control" id="exponentialnumber" name="exponentialnumber">
<option>SELECT THE OPTIONS</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
</div>
</div>
</div>
</div>
<button type="button" id="exponentialbutton" name="exponentialbutton" class="btn btn-primary col-xl-6 text-center" style="align-self: center !important;" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
If you run the example, you'll see that only the most recently entered value is displayed in the <button>.

OK I think I have this refactored correctly, I changed the order of your indicators because they seemed backwards:
<div class="col-md-4 pr-md-4">
<div class="form-group">
<label for="sel1">Left Side Indicator:</label>
<select class="form-control" id="left_indicator_side_select-me" name="left_indicator_side_select-me">
<option>Select</option>
<option value="1">Moving Average</option>
<option value="2">Exponential Moving Average</option>
</select>
</div>
</div>
<div class="col-md-4 pr-md-4">
<div class="form-group">
<label for="sel1">Comparator:</label>
<select class="form-control" id="comparator_indicator" name="comparator_indicator">
<option>Select</option>
<option value="=">=</option>
<option value=">">></option>
<option value="<"><</option>
</select>
</div>
</div>
<div class="row block-9">
<div class="col-md-4 pr-md-4">
<div class="form-group">
<label for="sel1">Right Side Indicator:</label>
<select class="form-control" id="right_side_indicator_select-me" name="right_side_indicator_select-me">
<option>Select</option>
<option value="1">Moving Average</option>
<option value="2">Exponential Moving Average</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label for="sel1">Selected values</label>
<button type="button" id="moving_average_output" name="moving_average_output" class="btn-primary col-xl-12 form-control">Value goes here</button>
</div>
And here is the refactored JS (note that I removed the last two event handlers from your example, as they were not needed):
const output = {
left: '',
compare: '',
right: '',
toString: function() {
return `${this.left} ${this.compare} ${this.right}`;
},
};
let sideIndicator = '';
$("#left_indicator_side_select-me").on('change', function() {
sideIndicator = 'left';
if ($(this).val() == 1) {
$("#myModal_first").modal('show');
}else if($(this).val() == 2) {
$('#simple_moving_average').val('');
$("#myModal_second").modal('show');
}
});
$("#comparator_indicator").on('change', function() {
output.compare = $(this).val();
$("#moving_average_output").text(output.toString());
});
$("#right_side_indicator_select-me").on('change', function() {
sideIndicator = 'right';
if ($(this).val() == 1) {
$("#myModal_first").modal('show');
}else if($(this).val() == 2) {
$('#simple_moving_average').val('');
$("#myModal_second").modal('show');
}
});
$("#movingaveragebutton").on('click', function(event) {
event.preventDefault();
output[sideIndicator] = $("#simple_moving_average").val();
$("#moving_average_output").text(output.toString());
});
$("#exponentialbutton").on('click', function(event) {
event.preventDefault();
exponentialstring = $("#exponentialstring").val();
exponentialnumber = $("#exponentialnumber").val();
output[sideIndicator] = exponentialstring + ',' + exponentialnumber;
$("#moving_average_output").text(output.toString());
});
Here's a JSFiddle where you can work with it and see if this solution meets your needs.
Brief Explanation
I created an object, output which will hold the text of the #moving_average_output <button> element. The properties will hold the text from the elements of the same name on the page:
const output = {
left: '',
compare: '',
right: '',
toString: function() {
return `${this.left} ${this.compare} ${this.right}`;
},
};
So, output.left will have the text content from this HTML element:
<div class="col-md-4 pr-md-4">
<div class="form-group">
<label for="sel1">Left Side Indicator:</label>
<select class="form-control" id="left_indicator_side_select-me" name="left_indicator_side_select-me">
<option>Select</option>
<option value="1">Moving Average</option>
<option value="2">Exponential Moving Average</option>
</select>
</div>
</div>
This works by creating a variable sideIndicator in the global scope and setting it to the side of the dropdown that was clicked in your 'change' event handlers. Here is the example for the #left_indicator_side_select-me event handler:
let sideIndicator = '';
$("#left_indicator_side_select-me").on('change', function() {
sideIndicator = 'left';
if ($(this).val() == 1) {
$("#myModal_first").modal('show');
}else if($(this).val() == 2) {
$('#simple_moving_average').val('');
$("#myModal_second").modal('show');
}
});
We can then use bracket notation to dynamically assign the value of the #simple_moving_average button and the #exponentialstring and #exponential number to the correct side in the output object:
$("#movingaveragebutton").on('click', function(event) {
event.preventDefault();
output[sideIndicator] = $("#simple_moving_average").val();
$("#moving_average_output").text(output.toString());
});
$("#exponentialbutton").on('click', function(event) {
event.preventDefault();
exponentialstring = $("#exponentialstring").val();
exponentialnumber = $("#exponentialnumber").val();
output[sideIndicator] = exponentialstring + ',' + exponentialnumber;
$("#moving_average_output").text(output.toString());
});
The call to output.toString() will return the correctly formatted string as the button text.
Another Possible Solution
As an aside, you are doing some repetitive things in your version, which I didn't change in my refactor above. If I were approaching this project, I would do things a little differently in my JS. Here's another way of looking at things:
const movingAverageOutput = document.getElementById('moving_average_output');
const simpleMovingAverage = document.getElementById('simple_moving_average');
const output = {
left: '',
compare: '',
right: '',
toString: function() {
return `${this.left} ${this.compare} ${this.right}`;
},
};
const triggerModal = (val) => {
if (val == 1) return $("#myModal_first").modal('show');
if (val == 2) {
simpleMovingAverage.value = '';
$("#myModal_second").modal('show');
}
};
let sideIndicator = '';
const setSideIndicator = (id) => {
if (id === 'left_indicator_side_select-me') return sideIndicator = 'left';
if (id === 'right_side_indicator_select-me') return sideIndicator = 'right';
};
window.addEventListener('change', function(e) {
triggerModal(e.target.value);
setSideIndicator(e.target.id);
});
$("#comparator_indicator").on('change', function() {
output.compare = $(this).val();
movingAverageOutput.textContent = output.toString();
});
$("#movingaveragebutton").on('click', function(event) {
output[sideIndicator] = simpleMovingAverage.value;
movingAverageOutput.textContent = output.toString();
});
$("#exponentialbutton").on('click', function(event) {
exponentialstring = $("#exponentialstring").val();
exponentialnumber = $("#exponentialnumber").val();
output[sideIndicator] = exponentialstring + ',' + exponentialnumber;
movingAverageOutput.textContent = output.toString();
});
And here is a JSFiddle of that version if you want to mess around with it.

Create 2 functions like bellow
Function 1 :
$(document).ready(function(){
$('#my_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_data.php", //This is your page which inserts data in db
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#error_message').html(data.error);
load_my_data(); //This is second function name
}
}
})
});
Now ! we are ready for second function here
load_my_data();
function load_my_data()
{
$.ajax({
url:"fetch_data.php",
method:"POST",
success:function(data)
{
$('#display_data').html(data);
}
})
}
});
Create all your php and html codes in fetch_data.php when data submited in modal it will auto display your data in
<div id="display_data"></div>
And This div will display errors
<div id="error_message"></div>
See this comment system as an example it works same way as you want : https://www.webslesson.info/2017/12/comments-system-using-php-and-ajax.html

Related

Unable to hide and show fields with select

I am trying to show and hide fields with respective selected value from tag. But it is not working. This same code is working perfectly in my other site. But it is not working here, don't know which thing i am missing. Here is the code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 col-sm-12 col-lg-12">
<label>Product Type <sup>*</sup></label>
<div class="select-wrp">
<script>
$('select')
.change(function () {
if ($(this).val() === 'single') {
$('.single').show();
$('.multiple').hide();
} else {
$('.multiple').show();
$('.single').hide();
}
})
.change();
</script>
<select name="product_type">
<option value="single">Single</option>
<option value="multiple">Multiple</option>
</select>
</div>
</div>
<div class="col-md-12 col-sm-12 col-lg-12">
<input class="single" name="single" type="text" placeholder="100" />
<input class="multiple" name="multiple" type="text" placeholder="100" />
</div>
Your script needs to be told to wait for the window to be loaded first. You can use jQuery to do this by simply adding $(() => { ... }) around your existing script:
$(() => {
$('select').change(function () {
if ($(this).val() === "single") {
$('.single').show();
$('.multiple').hide();
} else {
$('.multiple').show();
$('.single').hide();
}
}).change();
});
Natively, you would use window.onload = () => { ... }; instead.

How to Submit a Form by using a button at the same time click event on anchor link?

I have a from with button to submit it. Now i would like to pass same variables to another page to inset them in database. For that, i would like to pass the variables using an anchor link with GET with id's.
But how do it add an anchor link to the form where when i submit the form using the button the anchor link also gets triggered..
function splitAndResolve() {
var errorIds = [];
$('[name="error-selection-checkboxes"]:checked').each(function() {
errorIds.push($(this).val().split("-")[1]);
});
var taskVersion = 1;
if (errorIds.length > 0 && errorIds.length < $('[name="error-selection-checkboxes"]').length) {
var dataObj = {
'errorReportIdsToRemove': errorIds,
'user': 'user#mail.com'
};
var baseUrl = $(location).attr("href").substring(0, $(location).attr("href").lastIndexOf('/') + 1);
var splitTaskResponse = $.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70/split",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
}).responseJSON;
var taskId = splitTaskResponse.newTaskId;
// We need to update the version without which version on the UI and the DB are different.
taskVersion = splitTaskResponse.currentTaskPostSplit.version;
window.open(baseUrl + taskId, '_blank');
}
dataObj = {
'taskResolutionStatus': $("#inputResolution").val(),
'taskResolutionStatusDetail': $("#inputResolutionDetail").val(),
'taskResolutionNote': $("#inputNotes").val(),
'changeset': $("#inputChangeset").val(),
'requiresReview': $("#requiresReviewCheckBox").is(':checked'),
'version': taskVersion
};
$.ajax({
url: "/task/3f2456c6b44c3b29c651f8d55c1bb34ac4da11bb6d605a00629e79f2a95c4a70",
type: "POST",
data: dataObj,
async: false,
error: function(xhr, status) {
if (xhr.status == 400) {
window.location.href = "/400";
alert("Failed resolving the task, please retry upon reload.");
} else {
window.location.href = "/500";
alert("Failed resolving the task, please retry upon reload.");
}
}
});
enableStatusDropdown();
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal clearfix" onsubmit="return splitAndResolve()">
<div class="form-group">
<label for="changeset" class="col-sm-2 control-label">Changeset</label>
<div class="col-sm-10">
<input class="form-control" type="text" name="changeset" id="inputChangeset" readonly="">
</div>
</div>
<div class="form-group">
<label for="taskResolutionStatus" class="col-sm-2 control-label">Resolution</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatus" id="inputResolution">
<option disabled="" selected="" value=""> -- Choose one -- </option>
<option value="ESCALATE">Escalate</option>
<option value="ALREADY_FIXED_IN_OSM">Already fixed in osm</option>
<option value="NOT_ENOUGH_INFORMATION">Not enough information</option>
<option value="NO_FIX_REQUIRED">No fix required</option>
<option value="FIXED">Fixed</option>
</select>
</div>
</div>
<div class="form-group" id="inputResolutionDetailDropdown">
<label for="taskResolutionStatusDetail" class="col-sm-2 control-label">Detail</label>
<div class="col-sm-10">
<select class="form-control resolutionDropdown" name="taskResolutionStatusDetail" id="inputResolutionDetail">
<option value="LOW_PRIORITY_AREA">Low priority area</option>
<option value="KNOWN_BUG">Known bug</option>
<option value="ERROR_BASED_ON_BAD_DATA">Error based on bad data</option>
<option value="TRUE_EXCEPTION">True exception</option>
</select>
</div>
</div>
<div class="form-group">
<label for="taskResolutionNote" class="col-sm-2 control-label">Notes</label>
<div class="col-sm-10">
<textarea class="form-control" name="taskResolutionNote" id="inputNotes" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<label for="requiresReview" class="col-sm-2 control-label">Requires review</label>
<div class="col-sm-2">
<input class="form-control" name="requiresReview" type="checkbox" style="box-shadow: none" id="requiresReviewCheckBox">
</div>
</div>
<input id="taskResolutionButton" type="submit" class="btn btn-primary">
<button id="taskCancelButton" type="button" class="btn btn-default" onclick="hideResolutionOverlay()">Cancel</button>
</form>
<input id="taskResolutionButton" type="submit" class="btn btn-primary" onclick="$('#your_form_id').submit();>

How to display a table in a popup box with JavaScript?

I have the form below, with 4 comboboxes "Metier" "tache" "tacrification" et "technicien", I select a Metier and a tache, after this I want that a popup box appears and show me a table that contains all the "techniciens" and their "tarification" (of course only the "techniciens" that are related with the "tache" already selected.)
After this I select a "technicien" from that table a now the form is completely filled with the "technicien" and it's "tarification".
iterventioncontroller
public function create()
{
$client = client::orderBy('id', 'asc')->get();
$metiers = metier::orderBy('id', 'asc')->get();
$technicien = Technicien::orderBy('id', 'desc')->get();
$tarifications = tarificationtache::orderBy('id', 'desc')->get();
return view('intervention.create')->with('technicien', $technicien)-
>with('client',$client)-
>with('metiers',$metiers)->with('tarifications',$tarifications);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(InterventionRequest $request)
{
$intervention = new Intervention();
$intervention ->date_intervention =$request-
>input('date_intervention');
$intervention ->description =$request->input('description');
$intervention ->duree_prevu =$request->input('duree_prevu');
if($request->has('statut')){
$intervention->statut = $request->input('statut');
}else{
$intervention->statut = 0;
}
$intervention ->technicien_id = $request->input('technicien_id');
$intervention ->client_id = $request->input('client_id');
$intervention ->tarification_id = $request->tarification_id;
$intervention->save();
return redirect('intervention');
}
create.blade.php
#extends('Layouts/app')
#extends('Layouts/master')
#section('content')
<!-- jQuery -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var getTachesByMetierUrl = "{{url('/tachesbymetier')}}";
var getAdresseByClientUrl = "{{url('/adressebyclient')}}";
var getTarificationsByTacheUrl = "{{url('/tarificationsbytache')}}";
var getTechniciensByTarificationtacheUrl = "
{{url('/techniciensbytarificationtache')}}";
//console.log(getMetiersByTechnicienUrl,getTachesByMetierUrl,getTarificationsByTacheUrl);
function getAdresseByClient(val) {
if(val.length>0) {
var client_id = val;
$.get(getAdresseByClientUrl+'/'+client_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.adresses,function(index,item) {
html+='<option
value="'+item.id+'">'+item.code_postal+'</option>';
});
$('#adresses').html(html);
});
}
}
function getTachesByMetier(val) {
if(val.length>0) {
var metier_id = val;
$.get(getTachesByMetierUrl+'/'+metier_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.taches,function(index,item) {
html+='<option
value="'+item.id+'">'+item.libelle_tache+'</option>';
});
$('#taches').html(html);
});
}
}
function getTarificationsByTache(val) {
if(val.length>0) {
var tache_id = val;
$.get(getTarificationsByTacheUrl+'/'+tache_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.tarifications,function(index,item) {
html+='<option
value="'+item.id+'">'+item.tarif+'</option>';
});
$('#tarifications').html(html);
});
}
}
function getTechniciensByTarificationtache(val) {
if(val.length>0) {
var tarificationtache_id = val;
$.get(getTechniciensByTarificationtacheUrl+'/'+tarificationtache_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.techniciens,function(index,item) {
html+='<option value="'+item.id+'">'+item.id+'</option>';
});
$('#techniciens').html(html);
});
}
}
#if(count($errors))
<div class="alert alert-danger" role="alert">
<ul>
#foreach($errors ->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
</div>
#endif
<div class="container">
<div class="row"></div>
<div class="col-md-10">
<h1>Ajout Intervention</h1>
<form action=" {{url ('intervention') }}" method="post">
{{csrf_field()}}
<div class="form-group">
<label for="client">Client</label>
<select onchange="getAdresseByClient(this.value)"
name="client_id" id="client"
class="form-control">
<option value="">-Select-</option>
#foreach($client as $t)
<option value="{{$t->id }}">
{{$t->user->nom}}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">date intervention</label>
<input class="form-control" type="date" id="example-date-
input" name
="date_intervention" value="{{old('date_intervention')}}">
</div>
<div class="form-group">
<label for="">description</label>
<input type="text" name ="description" class="form-
control"value="
{{old('description')}}">
</div>
<div class="form-group">
<label for="">duree_prevu</label>
<input class="form-control" type="datetime-local" name
="duree_prevu" value="
{{old('duree_prevu')}}">
</div>
<div class="form-group">
<div class="col-md-12">
<div class="col-md-4">
<label>Metier: </label>
<select onchange="getTachesByMetier(this.value)"
style="width: 200px"
class="productm form-control" id="metiers">
<option value="">-Select-</option>
#foreach($metiers as $t)
<option value="{{$t->id }}">
{{$t->libelle_metier}}
</option>
#endforeach
</select>
</div>
<div class="col-md-4">
<label>tache: </label>
<select onchange="getTarificationsByTache(this.value)"
style="width: 200px"
class="productname form-control" name="tache" id="taches">
<option value="">-Select-</option>
</select>
</div>
<div class="col-md-4">
<label>tarification: </label>
<select
onchange="getTechniciensByTarificationtache(this.value)"
style="width:
200px" class="productname form-control" name="tarificationtache_id"
id="tarifications">
<option value="">-Select-</option>
</select>
</div>
<div class="col-md-4">
<label>technicien: </label>
<select style="width: 200px" class="productname
form-control"
name="technicien_id" id="techniciens">
<option value="">-Select-</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datepicker/1.5.0/css/bootstrap-
datepicker.css" rel="stylesheet">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datepicker/1.5.0/js/bootstrap-
datepicker.js"></script>
#endsection
You might want to look into bootstrap 4 modal.

Show / Hide Elements within the same parent div

I'm having trouble getting a div ('.option-other') within a parent group ('.other-row') to show/hide when the corresponding option of the select element ('.select-toggle') is selected. Right now if "other" is selected from either question set 1 or 2 it will show both of the '.option-other' divs. I tried using .parent() and .closest() as described in this solution, but can't seem to figure out the proper way to utilize it for this use case.
$(".select-toggle").change(function() {
var oth = false;
$(".select-toggle option:selected").each(function() {
if ($(this).val() == "other") oth = true;
});
if (oth) $('.option-other').show();
else $('.option-other').hide();
// tried this method as well but still doesnt work
// if (oth) $(this).closest('.other-row').children('.option-other').show();
// else $(this).closest('.other-row').children('.option-other').hide();
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Question set 1 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you eat?</label>
<select class="select-toggle" multiple>
<option>Pizza</option>
<option>Cake</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
<!-- Question set 2 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you drink?</label>
<select class="select-toggle" multiple>
<option>Water</option>
<option>Soda</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
// you wrote:
// tried this method as well but still doesnt work
// if (oth) $(this).closest('.other-row').children('.option-other').show();
// else $(this).closest('.other-row').children('.option-other').hide();
You're close, but $.children only selects direct children of each .other-row. Since .option-other is inside .col inside .other-row, $.children can't see it. Use $.find instead.
// your original code:
var oth = false;
$(".select-toggle option:selected").each(function() {
if ($(this).val() == "other") oth = true;
});
This sets one visibility value for the entire page: if at least one "other" option is selected, anywhere, show all the text inputs. The change event is fired for the <select> that actually changed, so focus your efforts there:
var oth = false;
$(this).children("option:selected").each(function() {
if ($(this).val() == "other") oth = true;
});
if (oth) $(this).closest('.other-row').find('.option-other').show();
else $(this).closest('.other-row').find('.option-other').hide();
This works, but it could be cleaner. Showing or hiding an element based on a boolean is a common enough requirement that jQuery has a function for it: $.toggle. You can replace the if/else lines with
$(this).closest('.other-row').find('.option-other').toggle(oth);
Your $.each loop does one thing: set oth if there exists at least one selected <option> with a value of "other". You can get the same logic as a one-liner by using an attribute selector:
var oth = ($(this).find('option:checked[value="other"]').length !== 0);
(I changed :selected to :checked because you're already filtering on option elements, and :selected has a performance penalty.)
The final version:
$(".select-toggle").change(function() {
var oth = ($(this).find('option:checked[value="other"]').length !== 0);
$(this).closest('.other-row').find('.option-other').toggle(oth);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Question set 1 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you eat?</label>
<select class="select-toggle" multiple>
<option>Pizza</option>
<option>Cake</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
<!-- Question set 2 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you drink?</label>
<select class="select-toggle" multiple>
<option>Water</option>
<option>Soda</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like" />
</div>
</div>
</div>
Vanilla JS version:
document.querySelectorAll('.select-toggle').forEach(el => {
el.addEventListener('change', evt => {
const oth = evt.target.querySelector('option:checked[value="other"]');
evt.target
.closest('.other-row')
.querySelector('.option-other')
.style.display = (oth ? '' : 'none');
});
// trigger change event programmatically
const event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
el.dispatchEvent(event);
});
Here is a solution that is a little clunky but I did it relatively quick. It's kind of a work around for having to know which of your two selectors with the same class had been selected.
Here is a working example using your code.
$(".select-toggle").change(function () {
var oth = false;
$(".select-toggle option:selected").each(function () {
if ($(this).val() == "otherFood") {
oth = true;
$('.option-other-food').show();
} else {
$('.option-other-food').hide();
};
if ($(this).val() == "otherDrink") {
oth = true;
$('.option-other-drink').show();
} else {
$('.option-other-drink').hide();
};
});
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Question set 1 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you eat?</label>
<select class="select-toggle" multiple>
<option>Pizza</option>
<option>Cake</option>
<option value="otherFood">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other-food">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like"/>
</div>
</div>
</div>
<!-- Question set 2 -->
<div class="wrapper other-row">
<div class="col">
<div class="form-group">
<label>What stuff do you drink?</label>
<select class="select-toggle" multiple>
<option>Water</option>
<option>Soda</option>
<option value="otherDrink">Other</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group option-other-drink">
<label>Other</label>
<input type="text" placeholder="what other stuff do you like"/>
</div>
</div>
</div>
Cheers!

How to clear old value from checkbox before next try?

I wrote my JavaScript code to get a value with JSON function to show in a checkbox, but every time I try with new options the old values still exist in the check box. I want to clear the checkbox before the next try. I marked the problem area in the code below:
HTML:
<div class="panel-body">
<div class="form-group">
<label for="field-1" class="col-sm-3 control-label" >Select Group</label>
<div class="col-md-2">
<select class="form-control" name="perms" onchange="OnSelectionChange(this)">
<option>Choice your group</option>
{foreach $perms as $perm}
<option value="{$perm.pID}">{$perm.title}</option>
{/foreach}
</select>
</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<strong>Edite Permisions:</strong>
<br />
<br />
</div>
<div class="col-sm-6" style="width:100%;">
<ul class="icheck-list">
{foreach $rps as $rp}
<li>
<input type="checkbox" name="updatePERM[]" id="{$rp.id}" value="{$rp.id}">
<label style="padding-left: 5px;vertical-align: middle;" >{$rp.rname}</label> <pre>{$rp.rdes}</pre>
</li>
{/foreach}
</ul>
</div>
</div>
</div>
</div>
JS:
function OnSelectionChange (select) {
var selectedOption = select.options[select.selectedIndex];
var url = "./include/getPerms.php?key="+selectedOption.value+"";
$.getJSON(url, function(data) {
$.each(data.rules, function(i, rule) {
// MY PROBLEM LINE: HOW I CAN DO THIS ?
if input:checkbox.val() != rule.id => set attr('checked', false)
else if input:checkbox.val() == rule.id => set attr('checked', true)
// HOW I CAN DO THIS ?
});
});
}
function OnSelectionChange(select) {
var selectedOption = select.options[select.selectedIndex];
var url = "./include/getPerms.php?key=" + selectedOption.value + "";
$.getJSON(url, function (data) {
// Default make all checkbox un-checked.
$("input:checkbox").prop("checked", false)
$.each(data.rules, function (i, rule) {
// If rule.id matches with the checkbox values then make those checkbox checked
$(":checkbox[value="+rule.id+"]").prop("checked",true);
});
});

Categories