Thanks to this post I've achieved to hide a dropdown menu when a value from a selectfield it's selectd:
$(function () {
var selectField = $('#id_type_contract'),
verified = $('#id_mod_contracts');
function toggleVerified(value) {
value == 'Modification' ? verified.show() : verified.hide();
}
// show/hide on load based on pervious value of selectField
toggleVerified(selectField.val());
// show/hide on change
selectField.change(function() {
toggleVerified($(this).val());
});
});
})(django.jQuery);
But it doesn't work as I wanted: Image , because still remains its label and 'Add' button (green cross). So, I think the best way to proceed is to hide the entire div, am I right?
html
<div class="form-row field-mod_contracts">
<div>
<label for="id_mod_contracts">Modification:</label>
<select id="id_mod_contracts" name="mod_contracts" style="display: none;">
<option value="" selected="selected">---------</option>
<option value="4">Contract foo</option>
<option value="7">Contrato bar</option>
<option value="8">contract CCCC</option>
</select> <img src="/static/admin/img/icon_addlink.gif" width="10" height="10" alt="Add another">
</div>
</div>
How could I adapt the above JavaScript function? Is there any other better option?
Either do as #Aumo suggest, unless you have the class field-mod_contracts on more elements (then it would hide them all).
If so you can instead use:
verified = $('#id_mod_contracts').parent();
This will select the inner most div
or:
verified = $('#id_mod_contracts').closest('.field-mod_contracts');
This will select the outer most div
Two hide the whole input section, change:
verified = $('#id_mod_contracts');
to
verified = $('.field-mod_contracts');
Related
I searched the net and tried all solutions for similar questions from SO, but just can't get this one working.
I am working in Django admin, and I have RadioSelect widget for the field is_valid, with two radio buttons in the form:
<div class="form-row field-is_valid">
<div>
<label for="id_is_valid_0">Is it valid?</label>
<ul id="id_is_valid" class="inline">
<li><label for="id_is_valid_0"><input type="radio" name="is_valid" value="True" id="id_is_valid_0" checked>
Yes
</label>
</li>
<li><label for="id_is_valid_1"><input type="radio" name="is_valid" value="False" id="id_is_valid_1">
No
</label>
</li>
</ul>
</div>
</div>
<div class="form-row field-not_valid_reason">
<div>
<label for="id_not_valid_reason">Reason:</label>
<select name="not_valid_reason" id="id_not_valid_reason">
<option value="" selected>Choose</option>
<option value="Expired">Expired</option>
<option value="Not adopted">Not adopted</option>
<option value="Unknown">Unknown</option>
</select>
</div>
</div>
I want to hide a class .field-not_valid_reason when 'Yes' (True) is checked (which is default for is_valid field) and show it when I click 'No'. This I accomplished.
Here is my jQuery code:
(function($) {
$(function() {
var isValid = $('input[type=radio][name=is_valid]'),
notValidReason = $('.field-not_valid_reason'),
function toggleFields(value) {
if (value === 'True') {
notValidReason.hide(250);
} else {
notValidReason.show(250);
}
}
// show/hide on load based on previous value of isValid
toggleFields(isValid.val());
// show/hide on change
isValid.change(function() {
toggleFields($(this).val());
alert(isValid.val());
});
});
})(django.jQuery);
But, for some reason, after the object is saved in the database with the is_valid field False, when I am on the change page of that object, the class .field-not_valid_reason is hidden, albeit active radio button is set to "No" (False).
Can you help, please?
In your current jquery code you where using alert(isValid.val()); to see which option is selected but this will give you first value only so to get current value which user has selected use $(this).val().
Then , onload you where getting right value for radio but the div was still hidden because you are again passing toggleFields(isValid.val()); which will give you first value only .So , to overcome this pass radio value which is checked i.e : $("input[name='is_valid']:checked").val() .
I have the following code:
https://jsfiddle.net/rmxpq2z0/
<div class="swiper-pagination"></div>
<div id="quote-form" class="quote-form">
<div class="container">
<div class="range range-xs-center range-lg-right">
<div class="cell-xs-10 cell-sm-8 cell-lg-5 text-left offset-top-0">
<div class="inset-lg-left-70">
<div class="quote-form-body">
<div>
<h3 class="text-bold">Get a FREE Quote!</h3>
</div>
<div class="offset-top-25">
<p>Please select your repair from the drop down boxes for an instant quote.</p>
</div>
<div class="offset-top-20">
<div class="form-group">
<select data-minimum-results-for-search="Infinity" class="form-control select-filter" id="console">
<option value="selectconsole">Select My Console</option>
<option value="ps4">PS4</option>
<option value="xboxone">Xbox One</option>
</select>
</div>
<div class="form-group">
<select data-minimum-results-for-search="Infinity" class="form-control select-filter" id="model">
</select>
</div>
Get My Quote
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
ps4models = new Array("Select My Model", "PS4 (Release Model)", "PS4 Slim", "PS4 Pro");
xboxonemodels = new Array("Select My Model", "Xbox One (Release Model)", "Xbox One Slim", "Xbox One Scorpio");
populateSelect();
$(function() {
$('#console').change(function() {
populateSelect();
});
});
function populateSelect() {
console = $('#console').val();
$('#model').empty();
$('#model').html('');
if (console == 'ps4') {
ps4models.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
$('#model').trigger("chosen:updated");
$('#model').find('option:first').attr('selected', 'selected');
});
}
if (console == 'xboxone') {
xboxonemodels.forEach(function(t) {
$('#model').append('<option>' + t + '</option>');
$('#model').trigger("chosen:updated");
$('#model').find('option:first').attr('selected', 'selected');
});
}
</script>
It works perfectly in the jsfiddle, but when I post the code to the website, it doesn't work.
It DOES populate the dropdown box, but it won't auto select the first option in the second box, and it won't remove any previous option that was selected.
For example, if I select an option in the first box, the second box stays empty until I select something. The first option should be auto selected. Also if I select something in the second box, and then change the selection in the first box, the second box option stays there, instead of being reset.
It is the EXACT same code, no changes at all. Is it possible the CSS is interfering with it?
Any help would be greatly appreciated.
UPDATE
Thanks to DanielH! It turns out the template was using Select2 jquery plugin. His code worked perfectly.
Solution 1:
Since you are using select2, add $('#model').change(); at the end of your console dropdown's select2 config should trigger the update every time you update the model dropdown list.
Solution 2:
If you have no control over the select2 or not sure where to find it, the following also gonna work, add a onchange event to the parent dropdown console:
$( document ).ready(function() {
$('#console').on('change', function(){
$('#model').val('selectmodel');
$('#model').change();
})
});
I've got the follwoing HTML structure (I do not have the IDs of the following elements because they are dynamically created):
<fieldset>
<div class="classA">
<select onchange="updateInputBox()">
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
</selects>
</div>
<div class="classB">
<input data-myAttribute="case1">
</div>
<div class="classC">
<a type="button">
<i class="fa fa-remove">x</i>
</a>
</div>
</fieldset>
The filedset and it's children is dynamically created. I want to change the attribute in the inputBox depending on what the user selected in the selectBox.
Here is an example how I would have done if the element fieldset would not have been dynamic (the following contains elements have IDs, but only because I want to demonstrate what I want; in reality I don't have IDs because they are dynamically created by clicking a button, that I do not show here):
https://jsfiddle.net/thadeuszlay/6bsgazvv/4/
But unfortunately I don't have the id of the fieldset, because it is dynamically created. Is there a way how you can get the position of the current element?
I tried to pass itself in the updateInputBox-function:
<select id="selectBox" onchange="updateInputBox('+ this +')">
I also tried with jQuery:
$(this).parent().parent()
but in both cases the console would say
"Unexpected identifier"
Update:
Inside the function doing something like this (currentElement is the selectBox/DropDownBox):
currentElement.parent().parent().setAttribute("data-myAttribute", "hello");
Uncaught TypeError: selectBox.parent is not a function
You can use jquery 'closest' for this as below.
HTML
<select id="selectBox" onchange="updateInputBox(this)">
JS
function updateInputBox(selectElm) {
var inputElm = $(selectElm).closest('fieldset').find('input');
inputElm.attr('data-myAttribute', $(selectElm).val());
}
// instead of inline onchange event and the above code, you can use the below to trigger the event
$(document).on('change', 'fieldset select', function () {
var inputElm = $(this).closest('fieldset').find('input');
inputElm.attr('data-myAttribute', $(this).val());
});
In updateInputBox, simply look at the selectedIndex of #selectBox
<select id="selectBox" onchange="updateInputBox(this)">
function
function updateInputBox(dropdowntBox) {
var inputBoxField = document.getElementById("inputBox").setAttribute("data-myAttribute", dropdowntBox.value);
}
Here is jquery version:solution
You need to trigger change() event for select with ID selectBox
$(document).on('change','select',function(){
var value=$(this).val();
$(this).parents('fieldset').find('input').attr('data-myAttribute',value);
});
When i select an item from a dropdownmenu id like to view it in a input field, if another item is selected i want to add this to the input field separated by a comma.
Currently this is the html:
<div>
<input type="text" id="box" placeholder="Using..." style="width: 400px">
<select style="width: 180px" id="drop">
<option value="" disabled selected>Select</option>
{% for stuff in stuffs%}
<option value="{{stuff}}" onclick="ApplyField(drop,box)">{{stuff}}</option>
{% endfor %}
</select>
</div>
and the javascript:
<script>
function ApplyField(drop_id,box_id)
{
var e = document.getElementById(field_id);
var selectedItem = e.options[e.selectedIndex].text;
if (document.getElementById(box_id).text == "")
document.getElementById(box_id).text = selectedItem;
else
document.getElementById(box_id).text = document.getElementById(box_id).text + "," + selectedItem;
}
</script>
But somehow my script wont set the input box item to the selecteditem altough the code seems logical to me. This is my first time writing javascript so its likely that i missed something trivial. Any help is appretiated.
I believe that your drop_id and box_id are not the correct way to select the element in JavaScript. Also not quite sure what is going on with the {{stuff}} template to be honest
Can you use jQuery? If so, have a look at http://www.w3schools.com/jquery/html_val.asp
I am having two issues with my table, One of them is that I want it to only show when I click a button but when i do it shows and then hides and the other is how do I send a parameter based on the select option to this createtable function
This is part of my code
<form class="form-inline" role="form">
<select multiple class="form-control" style = "width:250px"id = "theselect">
<option selected disabled> Chose a number </option>
<option> all </option>
<option> 1 </option>
<option> 2 </option>
</select>
<button type="submit" id = "load" class="btn btn-default">Load</button>
</form>
<div id ="test">
</div>
<script type = "text/javascript">
$(document).ready(function(){
$("#example").hide();
$("#load").click(function(e){
$("#example").show();
});
});
function createTable(param){
var contents = "<table id='example' class='display' cellspacing='0' width='100%' border>";
....
....
$('#test').append(contents); append it to div
}
$(document).ready(createTable(1));
</script>
Thank you
The reason that the table is getting hidden again is because you've set type="submit" on your button. This means that after the click event handler is done processing, it will submit the form, which causes the page to reload. When it reloads, the table is hidden again. If you change it to type="button" that will prevent that.
You can get the currently selected value of the select, using jquery, with this:
$('#theselect').val();
You can then pass this in to your createTable function (or just get the value using that code, from within the function itself).
Also, it's a really bad idea to create markup from within your JavaScript. It's going to make future maintenance a nightmare, and if it gets complex enough, it could start causing performance issues. It's much better to keep your markup separate, and then show/hide it as needed via JS.
Take a look at this example. It gets the selected values, and inserts them into a table, and table into the dom... HTH.
$(document).ready(function(){
$("#load").click(function(e){
var bits = $('#theselect').val();
$("#example").hide();
$('#test').html('');
createTable(bits)
$("#example").show();
});
});
function createTable(param){
var contents = "<table id='example' class='display' cellspacing='0' width='100%' border><tbody><tr><td>"+param+"</td></tr></tbody></table>";
$('#test').append(contents)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select multiple class="form-control" style = "width:250px"id = "theselect">
<option selected disabled> Chose a number </option>
<option> all </option>
<option> 1 </option>
<option> 2 </option>
</select>
<button id = "load" class="btn btn-default">Load</button>
<div id ="test"></div>
Try this:
$(document).ready(function(){
$("#load").click(function(e){
createTable($("#theselect").val());
$("#example").show(); // In case of class 'display' gives it 'display:none'
});
});
function createTable(param){
var contents = "<table id='example' class='display' cellspacing='0' width='100%' border>";
$('#test').append(contents);
}
#example doesn't exists at the beginning so I removed $("#example").hide().