Using print_media_templates i add some settings into wordpress gallery creator that allow me to chose gallery shortcode output (default gallery, masonry, slider) based on additional shortcode parameters.
My code so far :
<?php
add_action('print_media_templates', function(){ ?>
<script type="text/html" id="tmpl-custom-gallery-setting">
<label class="setting">
<span>Gallery Type</span>
<select name="type" data-setting="type" onchange="getval(this);">
<option value="default">Default</option>
<option value="masonry">Masonry</option>
<option value="slider">Slider</option>
</select>
</label>
<div id="slider-settings">
<label class="setting">
<span>Animation</span>
<select id="gallery-type" name="animation" data-settings="animation">
<option value=""></option>
<option value="fade">Fade</option>
<option value="slide">Slide</option>
</select>
</label>
</div>
</script>
<script>
jQuery(document).ready(function() {
wp.media.view.Settings.Gallery = wp.media.view.Settings.Gallery.extend({
template: function(view){
return wp.media.template('gallery-settings')(view)
+ wp.media.template('custom-gallery-setting')(view);
}
});
});
</script>
<?php
});
?>
It's only small part as example since there's much more options to each gallery type. Since there's lot of options i want to display only one corresponding to selected gallery type. In this example i want to display #slider-settings only when #gallery-type select value == "slider".
As for checking select value i found this code:
<script>
function getval(sel) {
if (sel.value == "slider") {
alert(sel.value);
}
}
</script>
with return selected type value (along with onchange="" on #gallery-type select) and display it if it's set to "slider".
But when i want to hide #slider-settings like :
function getval(sel) {
if (sel.value != "slider") {
$('#slider-settings').hide();
}
}
it's not hiding at all.
You have to handle native update function. Update function is fired for each label when a single change is made. (media-views.js line 7232)
var oldUpdate = wp.media.view.Settings.Gallery.prototype.update;
wp.media.view.Settings.Gallery.prototype.update = function(key) {
if( key === "type" ) {
var value = this.model.get( key );
if ( value === "slider" ) {
setTimeout(function(){
jQuery("#slider-settings").css({"display":"block"});
});
} else {
setTimeout(function(){
jQuery("#slider-settings").css({"display":"none"});
});
}
}
// Initialize native code.
oldUpdate.apply(this, arguments);
};
Somehow i managed to get it work by hiding #slider-settings using not jQuery but javascript :
<script>
function getval(sel) {
if (sel.value != "slider") {
document.getElementById('slider-settings').style.display = 'none';
} else {
document.getElementById('slider-settings').style.display = 'block';
}
}
</script>
But to get value it's has to change (since it's onselect=) so first time i display settings it's not hiding. And as i searched there's seems to be not anything like onload= i can use with .
Or is there a way to just reselect it on load ?
Related
I found an answer to my question here but it really doesn't work for me. I am very new to programming and quite not yet familiar using javascript. Sad to say, I've been trying to do this for quite a while.
What I want to do is to change the background of a div whenever I change the option in a select tag. Here's my .JSP code
Add Ons Type:
<select id="addOnsType" name="addOnsType" onchange="changePicture()">
<option selected disabled> select add ons</option>
<c:forEach var="addOnsType" items="${addOnsType}">
<option value="${addOnsType.addOnsTypeId}"> ${addOnsType.description} </option>
</c:forEach>
</select>
<div id="PictureDiv" style="height: 58px; width: 344px">
</div>
The addOnsTypeId has values of 1, 2 and 3.
While my javascript is written as (I've used what I saw in here)
function changePicture() {
var PictureDivBG = document.getElementById("PictureDiv");
var addOnsTypeSelected = document.getElementById("addOnsType");
if (addOnsTypeSelected.val() == 1) {
PictureDivBG.style.backgroundImage = "url('../images/cartoon1.jpg')";
} else if (addOnsTypeSelected.val() == 2) {
PictureDivBG.style.backgroundImage = "url('../images/cartoon2.jpg')";
} else if (addOnsTypeSelected.val() == 3) {
PictureDivBG.style.backgroundImage = "url('../images/cartoon3.jpg')";
}
};
Any help/hints/answers would be much appreciated. Thanks!
Follow up newbie question: I'm quite confused about javascript and jQuery, what's the difference?
addOnsTypeSelected is a dom element reference, it doesn't have the val() function, which is provided by jQuery.
You can get the jQuery object for those element using the id selector and get the value
function changePicture() {
var addOnsTypeSelected = $("#addOnsType").val(),
backgroundImage;
if (addOnsTypeSelected == 1) {
backgroundImage = "url('../images/cartoon1.jpg')";
} else if (addOnsTypeSelected == 2) {
backgroundImage = "url('../images/cartoon2.jpg')";
} else if (addOnsTypeSelected == 3) {
backgroundImage = "url('../images/cartoon3.jpg')";
}
$('#PictureDiv').css('background-image', backgroundImage);
};
But using jQuery event handlers, you can
jQuery(function() {
var imgs = {
1: 'url(//placehold.it/64/ff0000)',
2: 'url(//placehold.it/64/00ff00)',
3: 'url(//placehold.it/64/0000ff)'
}
$('#addOnsType').change(function() {
$('#PictureDiv').css('background-image', imgs[$(this).val()] || 'none');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Add Ons Type:
<select id="addOnsType" name="addOnsType">
<option selected disabled>select add ons</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<div id="PictureDiv" style="height: 58px; width: 344px">
</div>
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 am trying to update a list by using a toggle switch, but I cannot find the solution. Any inputs from you guys? any hint will be very appreciated :).
Important: the .ui-li list id is #myListView which is populated from the server with data-value as +item.Gender+ "female" or "male". I want to create a code that if user uses toggle off for male, then the list will update by only showing "female" value in the li. and vice versa.
So far, I have this (no working) code:
$(document).on("pagecreate", "#page-settings", function (){
$("#flip-1").on("change", function (){
if ($(this).val() == "off"){
$("#myListView").val($(item.Gender =="female")).listview( "refresh" );
}
});
});
And my HTML looks like this:
<div data-role="content" id="settingsPanel">
<div data-role="fieldcontain" id="menSelector" >
<label for="flip-1">Men</label>
<select name="flip-1" id="flip-1" data-role="slider"data-mini="true" class="genderSelect">
<option value="off"></option>
<option selected="selected" value="on"></option>
</select>
</div>
<div data-role="fieldcontain" id="womenSelector" >
<label for="flip-2">Women</label>
<select name="flip-2" id="flip-2" data-role="slider"data-mini="true" class="genderSelect">
<option value="off"></option>
<option selected="selected" value="on"></option>
</select>
</div>
Assuming your li has a data attribute for gender, e.g.
<li data-gender="female"></li>
Then when you flip a switch, first show all listitems:
$('#myListView li').show();
Then hide either male or female:
$('#myListView li[data-gender="male"]').hide();
UPDATE:
So, given your flip switches, handle the change event and call a function called ShowList() on each change. In ShowList() check which flip switches are on, and if one is on and the other is off, hide the gender that is off:
$(document).on("pagecreate", "#page1", function(){
$("#flip-1").on("change", function(){
if ($(this).val() == "off"){
$("#flip-2").val("on").slider( "refresh" );
}
ShowList();
});
$("#flip-2").on("change", function(){
if ($(this).val() == "off"){
$("#flip-1").val("on").slider( "refresh" );
}
ShowList();
});
});
function ShowList(){
var m = $("#flip-1").val() == "on";
var f = $("#flip-2").val() == "on";
$('#myListView li').show();
if (m && !f) {
$('#myListView li[data-gender="female"]').hide();
} else if (!m && f) {
$('#myListView li[data-gender="male"]').hide();
}
}
DEMO
I implement jquery multiselect and its working properly now i need to add extra feature that when a user select another option in dropdown ( check another checkbox ) then i want to get the value of the related option
in above picture in did not insert checkbox it is automatically inserted by jquery now i want that if i select the check =box with XYZ then i want to get the value of XYZ which is the id of XYZ
here is how i implemented it
<select multiple="multiple" id="CParent" name="parent" class="box2 required">
#foreach (var item in Model.Categories.OrderBy(c => c.Name))
{
if (Model.Coupon.Categoryid.Id == item.Id)
{
<option selected="selected" value="#item.Id">#item.Name</option>
}
else
{
<option value="#item.Id">#item.Name</option>
}
}
</select>
and it is how it looks like after rendering in browser source
Thanks in advance for helping me .
what i tried yet
$('#CParent input:checked').change(function () {
var parentid = $(this).val()+'';
var array = parentid.split(",");
alert(array);
getchildcat(array[array.length -1]);
});
});
Edit
Code to initialize multiselect
$("#CParent").multiselect({
header: "Choose only THREE items!",
click: function () {
if ($(this).multiselect("widget").find("input:checked").length > 3) {
$(warning).show();
warning.addClass("error").removeClass("success").html("You can only check three checkboxes!");
return false;
}
else if ($(this).multiselect("widget").find("input:checked").length <= 3) {
if ($(warning).is(":visible")) {
$(warning).hide();
}
}
}
});
try this
$('#CParent').val();
this will give you the selectbox value
OR
from docs
var array_of_checked_values = $("#CParent").multiselect("getChecked").map(function(){
return this.value;
}).get();
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
}