I'd like to know if it's possible for a select box to have two functions.
1.Redirects automatically when selecting an option using value.
2.Load content via ajax into the closest div using data-file.
<select class="loadurl">
<option value="#">Select</option>
<option value="contact.php">Contact</option>
<option value="about.php">About</option>
<option data-file="fans.php">Fans</option>
</select>
<div class="area"></div>
But when I tried the following script, the ajax option (Fans) didn't work but attempted to redirect instead. May I know how to have two functions in just one select box? Here's a demo.
$(".loadurl").bind('change', function () {
var selected = $(this).find('option:selected');
var loadfile =selected.data('file');
var area = $(".area");
$(this).next(".area").load(loadfile);
area.empty();
});
$('.loadurl').bind('change', function () {
window.location.href = $(this).val();
});
You need to use a conditional choice here - if the selected option has data-file then load the target in the area else reload the page.
var area = $(".area");
$(".loadurl").on('change', function () {
var selected = $(this).find('option:selected');
var loadfile = selected.data('file');
if (loadfile) {
area.empty();
$(this).next('.area').load(loadfile);
} else {
window.location.href = $(this).val();
}
});
Related
I'm using selectize plugin and trying to alert custom data-attribute.
I tried with several method but it alway indefined result
My select list :
<select name="location_work{{counter}}" id="location_work{{counter}}" class="list_type_op" data-md-selectize-inline required>
<option data-data='{"param": 0}' value="1">Construction</option>
<option data-data='{"param": 1,"name":"x"}' value="2">Puchase</option>
<option data-data='{"param": 2,"name":"x-y"}' value="3">Warranty</option>
</select>
And my js function
$(document).on('change', '.list_type_op', function () {
var selected_option = this.value;
var nbParam = $('option:selected', this).attr('data-param');
alert(nbParam); //is indefined
});
Select list is in Estimated price section on Type Column
Here my jsfiddle : Jsfiddle
Finally i get value of attribute with this :
$(document).on('change', '.list_type_op', function () {
var selected_option = this.value;
var nbParam = $(".selectize-dropdown-content").find(`[data-value='${selected_option}']`).attr('data-param');
alert(nbParam);
});
I search attribute in html code.
There is a website that I want to simulate user clicks on. In this website, there is the following div, let's call it div1, where there is a dropdown menu. There are actually other two similar divs (lets call them div2 and div3) following but I didn't place here for the simplicity. When you select one of the item in the dropdown menu in div1, the div2 is enabled (disabled by default in the beginning) and its menu content is fetched from database based on the item selected from the div1.
I can select the menu item using following script.
Code:
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].value== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
var number = document.getElementById('level1-option');
setSelectedValue(number, "p3");
However, when I do this, the div2 is never enabled. I tried jQuery code to emit change signal on the dropdown menu but it doesn't work. When I was debugging the below html code, I saw the button tag there and I immediately thought that it submits when there is click. However, I don't see any form. If I debug the website using chrome, I see that the code jumps different js files when I select an item in the menu. Could anyone guide me how I can find out which signal is triggered when an item is selected? Apparently they do some tricks in the website to prevent normal ways of clicking
Code:
<div data-custom-select="" class="custom-select focus">
<label for="level1-option" class="has-hidden-label label-text">Sections</label>
<span class="btn-select icon-down_thin">Choose a section</span>
<select class="categories-options" data-level="1" name="level1-option" id="level1-option" required="">
<option value="">Choose a section</option>
<option value="p1" data-href="/callback/discovery/p1/">P1</option>
<option value="p2" data-href="/callback/discovery/p2/">P2</option>
<option value="p3" data-href="/callback/discovery/p3/">P3</option>
<option value="p4" data-href="/callback/discovery/p4/">P4</option>
</select>
<span class="icon-down_thin"></span>
<button type="submit" class="category-submit ui-button-secondary ">Choose</button>
Usually you could use:
$("#level1-option").val(valueToSet).trigger("click")
or
$("#level1-option").val(valueToSet).trigger("change")
but it might depend on the rest of the code on the webpage.
Try ...
$(element).trigger('click');
... from jQuery.
Try dispatching onchange event once you have changed its value:
var number = document.getElementById('level1-option');
setSelectedValue(number, "p3");
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
number.dispatchEvent(evt);
Sorry, that I couldn't help with the overlay issue. Your markup is pretty complex.
Anyway, I coded a bit for the updating/fetching data from database. Please find below a demo of it.
The demo is also here at jsFiddle
The JSON data looks like this {"data": ["1st_1", "1st_2", "1st_3"]}
During my work I had one issue that wasn't that easy to solve, but another SO question helped here. If you'd only use the change event you can't trigger the first element to fetch your next data.
The counter trick works pretty well.
var dynamicOptions = (function () {
var url; // here you can add your url to the backend script
// urlList only required for demo because no backend available
var urlList = ['http://www.mocky.io/v2/54839e2a2f4b84a0041bba49',
'http://www.mocky.io/v2/54839e4c2f4b84a5041bba4a',
'http://www.mocky.io/v2/54839e6a2f4b84a9041bba4b'];
var cc = 0; // click counter
// e.g. $optionEl = $('#firstSelection');
// $nextOptionEl = $('#secondSelection');
function Selector($optionEl, $nextOptionEl) {
this.$optionEl = $optionEl;
this.$nextOptionEl = $nextOptionEl;
this.ajaxRequest = function (optionValue) {
return $.ajax({
type: 'GET', // later 'POST'
//data: {'data': optionValue}, // for posting
url: url,
contentType: "application/json",
dataType: 'jsonp',
context: this,
});
};
this.getData = function(value) {
url = urlList[value]; // simulating backend returns based on this value
var ajaxReq = this.ajaxRequest(value); // this.value not used in this demo
ajaxReq.success(this.jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
};
// handle click and change event. Source from here: https://stackoverflow.com/questions/11002421/jquery-event-to-fire-when-a-drop-down-is-selected-but-the-value-is-not-change
this.clickHandler = function ($element) {
//console.log($element);
var that = this;
return $element.click(function () {
//console.log('clicked');
cc++;
if (cc == 2) {
$(this).change();
cc = 0;
}
}).change(function (e) {
cc = -1; // change triggered
//console.log(this.value);
that.getData(this.value);
});
}
this.clickHandler($optionEl);
this.jsonCallback = function (json) {
var $nextEl = this.$nextOptionEl;
$nextEl.empty(); // clear selection
$nextEl.prop('disabled', false); // enable 2nd select
this.triggerChangeEvent(); // maybe a check if they really changed would be good
$.each(json.data, function (index, value) {
$('<option/>')
.val(index)
.text(value)
.appendTo($nextEl);
});
};
this.triggerChangeEvent = function () {
var event = jQuery.Event("optionsChanged");
event.context = this;
event.message = "Options changed, update other depending options";
event.time = new Date();
$.event.trigger(event);
};
}
return {
Selector: Selector
}; // make Selector public
})();
$(function () {
var $first = $('#firstSelection');
var $second = $('#secondSelection');
var $third = $('#thirdSelection');
// use our dynamic options selector class
var options12 = new dynamicOptions.Selector($first, $second);
var options23 = new dynamicOptions.Selector($second, $third);
$(document).on('optionsChanged', function (e) {
console.log("options changed", e);
var obj_id = e.context.id;
//console.log(obj_id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div>
<form role="form">
<div class="form-group">
<label>Please select first value:</label>
<select id="firstSelection" class="form-control">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="form-group">
<label>Please select second value:</label>
<select id="secondSelection" class="form-control" disabled="true">
<!-- fetched from server -->
</select>
</div>
<div class="form-group">
<label>Please select third value:</label>
<select id="thirdSelection" class="form-control" disabled="true">
<!-- fetched from server -->
</select>
</div>
</form>
</div>
I have this select tag:
<select name="test">
<option value="stack">Stack</option>
<option value="overflow" selected>Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>
For example I selected the overflow option. How can I auto select the prev option and next option of my selected option, with jquery?? I don't have to use the namo or the value, just select the previos or next option, whatever it is.
Thanks for help!!!
You can do it, if you add multiple attribute to the select
$('select').change(function () {
var i = $(this).find(":selected");
var arr = $(this).children();
i.next().prop('selected', true);
i.prev().prop('selected', true);
});
DEMO
I'm not sure I understand the use case, but here are two functions that will do what you want:
function selectPrev() {
// get the selected option
var $selected = $("select[name=test]").find('option:selected');
// remove the selected property
$selected.prop("selected", false);
// get previous option and add selected property
var $prev_option = $selected.prev().prop("selected", true);
}
function selectNext() {
// get the selected option
var $selected = $("select[name=test]").find('option:selected');
// remove the selected property
$selected.prop("selected", false);
// get next option and add selected property
var $next_option = $selected.next().prop("selected", true);
}
When an option is selected that wasn't previously, the onChange handler can detect this. How can a preselected option be detected (i.e., whether a select field has any option selected)? Is this possible without jQuery? Is there a handler, such as onSelected (not the same as onSelect for highlighted text) for this event?
Example:
<select onSelected="FunctionRunIfOptionSelected()">
<option> ... </option>
...
</select>
The preselected option will have been selected on page load. i.e., with the HTML dynamically rendered:
<option selected> ... </option>
If I understand, the task is to tell if an option has the selected attribute hard-coded into the HTML? If so, this should work:
function test () {
var opts = document.getElementById("myselect").options;
var i, len = opts.length;
for(i = 0; i < len; i++) {
if (opts[i].getAttribute("selected" ) != null ) { // opts[i] has the selected attribute
change_other_select(i); // pass the option index to your other function
break;
}
}
}
window.onload = test;
The trick is to distinguish between the selected property and the selected attribute, and also between a null value and an empty string.
var myselect = document.getElementByid('selectid');
myselect.options[myselect.selectedIndex];
To test for selected option on page load, you'll need to catch these in the window.onload handler
One the page is loaded you'll need to continue to use the onChange handler, but use selectedIndex property to test if this is populated with an index within your option list.
Alternatively give your options values in the HTML and check the values themselves. This will allow deterministic behavior when expanding the option list.
Yes, using the .options[] and .selectedIndex methods you can handle this cleanly and unobtrusively like so:
HTML
<select name="select" id="select">
<option value="">...</option>
<option value="1">One</option>
<option value="2" selected="selected">Two</option>
</select>
JavaScript
window.onload = function(){
var select = document.getElementById("select"), selected = select.value;
select.onchange = function(){
var val = select.options[select.selectedIndex].value;
if(val != selected) {
alert("Another value " + val + " was selected, which is not the same as the default value of " + selected);
} else {
alert("Same value as the default of " + selected + " was selected");
}
};
};
From within the JS, you can check and manipulate the val variable as you like.
You can detect if the select field does not have the default value selected like this:
var selects = document.getElementsByTagName("select");
for (i=0;i<selects.length;i++) {
if (selects[i].selectedIndex != 0) {
eval(selects[i].getAttribute("onSelected"));
}
}
I need to be able to hide an image that appears when clicking on an option within a select field ONLY if the value="" (nothing inside quotes). If the value="some_url" inside the option, then I want the image to show.
I have used the following code to SHOW the image when an option is clicked. But when using onClick, it shows the image even if the option value="".
Here is the Javascript I'm using:
function showImage() {
document.getElementById('openimg').style.display = 'block';
Here is the html:
<select name="" >
<option value="url" onclick="showImage();">Some_option_1</option>
<option value="">Some_option_2</option>
<option value="">Some_option_3</option>
</select>
<a href='url_2'><img src='images/some_img.jpg' id='openimg' style='display:none'></a>
I only inserted one onClick command inside one option, just to show that it works. It seems I need an if statement to "show if" or "hide if" along with the onClick command within each option.
this is how I would do it:
<script type="text/javascript">
function showImage()
{
var choice = document.getElementById('myDropDown').value;
if(choice.length > 0)
{
document.getElementById('openimg').style.display = 'block';
}
else
{
document.getElementById('openimg').style.display = 'none';
}
}
</script>
<select id="myDropDown" onchange="showImage()">
<option value="url">Some_option_1</option>
<option value="">Some_option_2</option>
<option value="">Some_option_3</option>
</select>
<a href='url_2'><img src='images/some_img.jpg' id='openimg' style='display:none'></a>
Um, are you asking how to use an if or how to determine what is selected?
First of all, use onchange event in the dropdown.
This is the LONGHAND way of doing it for illustration purposes.
function onChange(){
var mySelect = document.getElementById("my-select");
var selectedValue = "";
for( var i = 0; i < mySelect.length;i++){
if( mySelect[i].selected)
selectedValue = mySelect[i].value;
}
if( selectedValue == "whatever")
{
//do something
}
if( selectedValue == "ugh")
// do something else
}