jQuery styling function in loaded ajax content? - javascript

I'm loading some div content using a navigation and i've got most of the content working properly. However I'm now trying to set up:
http://www.bulgaria-web-developers.com/projects/javascript/selectbox/
On a select dropdown, however the styling is called using the following:
$(function () {
$("#select").selectbox();
});
And I can't see how I can I can apply:
$(document).on('mousedown', '.nav-link', function() {
To it for when it first appears? Any advice much appreciated, cheers.
UPDATE
Nevermind, i've done it.
SECOND UPDATE
Ok i've just found 2 problems. Firstly, I made it show by using:
if (href == 'requestedpage.php') {
$(function () {
$("#select").selectbox();
});
};
And when the page loads the first time, the selectbox is styled properly, however if you go to another page and then go back, it doesn't apply the style second time around?
The other problem i've got is that when you click on the options, the dropdown makes your selection, but all of the options in the select list remain in view.
HTML code is:
<select id="selectlist" name="selectlist" onchange="updatevariable(this.value)" tabindex="1">
<option value="">-- Select Quantity --</option>
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
</select>
Sorted problem 2 by removing onchange event!
Thanks in advance to anyone who can help me out.

If it's not applying the styling when you navigate back, it might be as simple as setting a flag in your callback.
One way to do this is to send a flag value to a hidden input field which will post to your server on page-submit. This means when you navigate back, you can check if the flag is there, if it is, apply the styling.
Alternatively, if you are building this application for browsers which support HTML5, you can save to the sessionStorage in your AJAX callback.
So, where you're checking the href, add this:
if (href == 'userarea-page1.php') {
$(function() {
$("#select").selectbox();
sessionStorage.selectFlag = "true";
});
};
Then, above your $("a.nav-link").click event (in your document.ready) you can check if this is has been set. If it has, apply the styling.
$(document).ready(function() {
if (sessionStorage.selectFlag == "true") {
$("#select").selectbox();
}
$("a.nav-link").click(
...
);
);
This will take care of maintaining the styling state between pages. Just make sure you clear the flag if you ever want to remove the styling, otherwise it'll be applied forever.

I'm not sure why you're setting the styling via javascript if you want it on page load, but if that is the way you're doing things try this may help:
$(document).ready(function() {
$("#select").selectbox();
);

Related

Selected attribute of select options is not updating automatically

I have multiple selects on my page, each has multiple options.
However, If I select an option then the attribute selected of the option is not updating. Shouldn't this happen automatically?!
Example:
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
By inspecting the DOM with the developer console, you should see, that the selected attribute is not changing even after selecting another option.
However I found a workaround. To solve this issue we can use this code:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
Example:
$(document).on("change","select",function() {
$("option[value=" + this.value + "]", this)
.attr("selected", true).siblings()
.removeAttr("selected")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="browsers">
<option value="Firefox">Bing</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
This works kind of. However, If I select another option than the default option, e.g. Chrome and reload the page, then the option Chrome is still selected even after reload, BUT the selected attribute still points to Internet Explorer!
Which is the best approach to solve this?
My idea is to run through all selects on $(document).ready() and select the option where the selected attribute points to.
But why does this all not happen automatically?
Is it a bug or a feature?
The selected attribute defines if an element should be selected on pageload. If you post a form with a select element, the chosen option will be the one posted, regardless of the initial selected element.
What do you need the selected-attribute for in your case?
Edit: Based on your comments I made a fiddle
Fiddle 1 https://jsfiddle.net/q3fpafov/1 selects like you want
Fiddle 2 https://jsfiddle.net/bge9bsa7/2/ only files available for a chosen language are shown
I hope it's somewhere along the lines of what you're looking for.
The reason for your option still being selected when you reload is browser based. But the selected-attribute does nothing for the usability of the option. Also, it won't change because you don't change the way the HTML-element itself is being rendered (at page load)
Note: selected="selected" is not necessary, simply selected attribute will work as well.
When present, select attribute specifies that an option in select should be pre-selected when the page loads.
Also, the pre-selected option will be displayed first in the drop-down list.
Those 2 should be only effects of the selected attribute.
Note the keywords - when the page loads. He is either there or not when a browser loads the page.
If you wanna make it dynamic you need to use JavaScript. What do you wanna achieve with this? Having attribute selected on the correct element when reloading page or programmatically select the correct element after the page has been loaded?
If you simply wanna make element selected there is easier way trough either value:
jQuery("#browsers[value='the value of the one you like']").attr('selected','selected');
Or by index (mind, indexes start at 0 not 1):
document.getElementById("browsers").selectedIndex = "2";
The problem before was, that after selecting an option and reloading the page, the option was remembered during page reload, even though the attribute selected pointed to another option.
I solved it by calling the function below everytime. The function finds out which is the truly selected option, even after page reload.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="downloadSelect" id="select_179">
<option value="-">Please select</option>
<option value="link_2748" selected="selected">Deutsch</option>
<option value="link_2749">Chinese</option>
</select>
<button onclick="return showSelectedOption('select_179');">Show Option Text</button>
<script>
function showSelectedOption(pSelectID)
{
var text;
$("#"+pSelectID)
.find("option")
.each(function(){
if ($(this).prop("selected")) {
text = $(this).text();
}
});
console.log(text);
}
</script>
You can check the value of the select when it changes to see what it has been changed to.
var select = document.getElementById('browsers');
select.addEventListener('change', function(e) {
localStorage.setItem('browser', this.value);
});
var browser = localStorage.getItem('browser');
if (browser) {
select.value = browser;
}
<select id="browsers">
<option value="Firefox">Firefox</option>
<option value="InternetExplorer" selected="selected">Internet Explorer</option>
<option value="Chrome">Chrome</option>
</select>
edit
So, I missed the part about storing the value so that it persists when the page is reloaded, and depending on the OP's use case, I would suggest using localStorage to save the value when it is changed, and to read from it when the page is reloaded.
I have edited the snippet to reflect this (code is simplified)

HTML select change value based on Database entry with vbhtml

I want to edit some Data in a HTML select Element:
<select id="Photoshop" name="Photoshop">
<option selected value= 0> </option>
<option value=2>Installieren</option>
<option value=0>Nicht Installieren</option>
</select>
I want to get this selected, based on the Value which is in the Database. (If I select Value 2, it should stay Value 2 after reload, now every time I reload it resets to 0)
I've tried different things with JavaScript (Newbie in js here), but it didn't work.
<script>
$(document).ready(function () {
$("#Photoshop").val("Model.Photoshop")
})
</script>
changes the value to Null
the code block from vbhtml wont want to work too. I can get the Data, but cant change it in the selectbox (doesn't "know" the selectbox)
There should be a another way, to get the Database Data, at the best without js. (Model.Photoshop should do its Job)
I haven't found something similar, which can fix this kind of problem. My researches were hopeless...
The solution is kinda simple.
<script src="~/Scripts/jquery-3.1.1.js"></script>
<script>
$(document).ready(function () {
$("#Photoshop").val("#Model.Photoshop")
})
</script>
as you can see, you just need to Type #Model.Photoshop, instead of Model.Photoshop.
If this Value is not in the select list, you will se a blank Space.
AR

JavaScript (JQuery): Cancelling a selection in select control in FireFox

In my application, I have a list of <select> controls. Change of selection in each of these controls can be made only after user confirmation. So I deal with it as follows:
<select onchange="changeSelect(this)" onmousedown="clickSelect(this)">
<option value="1" selected="true">A</option> // here is 'default' value 1
<option value="2" >B</option>
</select>
<select onchange="changeSelect(this)" onmousedown="clickSelect(this)">
<option value="1" >A</option>
<option value="2" selected="true">B</option> // here is 'default' value 2
</select>
// more select controls with arbitrary 'default' values, they can be added and removed dynamically
When the user clicks the select to choose another option, the clickSelect(this) method saves the currently chosen (old) selection:
function clickSelect(select) {
globalScope.previouslySelected = $(select).val();
}
And now, if the user really tries to change the selection, I ask the user for confirmation, and if she does not confirm, I use the saved value to restore the previous state:
function changeSelect(select) {
var response = confirm("Current changes to the threat log will be lost. Continue anyway?");
if (response == false) {
// change it back
$(select).val(globalScope.previouslySelected);
return;
}
}
}
Now, on IE, Chrome and Opera it works just fine. However, when I use Firefox, it does not work. THe reason is that FF calls the onmousedown handler twice during the selection -- first time when the user clicks to roll down the select control, and second time when she selects a new selection. Therefore the last remembered value of globalScope.previouslySelected will become the new selected value and not really the old one, as in other browsers.
I know using global variables is considered bad practice. This is not the issue here. Using any other storage will not make it work.
My only idea right now is to write a Firefox specific piece of code in the clickSelect(select) handler and ignore the second notification. However, for some reason the following code I found on stack overflow does not work:
if($.browser.mozilla) {
console.log("Olalala");
}
E.g., in Chrome it throws following exception:
Uncaught TypeError: Cannot read property 'mozilla' of undefined
So how can I make it work so that ti would only run in FF? Or if any of you guys have a better solution to the problem of confirmation, I would gladly hear it. Just remember, there is a dynamic set of select controls, not just a single one. It has to work for all of them. Plus they can be added or removed dynamically, so in a single page request their number can vary. User loads page with a single select control, presses a '+' button and adds another select control, etc., but the solution has to work uniformly with all the controls.
Is there a specific reason you're saving the currently selected option using the onmousedown listener? You can just initialize your global variable to hold the default option, and update it whenever a new selection is made.
Something like this:
HTML
<select id="mySelect" onchange="changeSelect(this)">
<option value="1" >A</option>
<option value="2" >B</option>
</select>
JS
var globalScope = {previouslySelected: $("#mySelect").val()};
function changeSelect(select) {
var response = confirm("Current changes to the threat log will be lost. Continue anyway?");
if (response == false) {
// change it back
$(select).val(globalScope.previouslySelected);
return;
}
globalScope.previouslySelected = $(select).val();
}
EDIT
I noticed that on Firefox, the second mousedown event's target is the option, so you can use the following code to ignore the event in this case:
$("select").mousedown(function(e) {
if ($(e.target).is('option'))
return;
globalScope.previouslySelected = $(this).val();
});
With this code you can remove the onmousedown registration from your DOM.

Clear/reset change function after click function

I am using change for my inputs and then I'm asking questions. All of my code is inside a click function. I would like to let the user answer the questions again, and for there previous data not be there. I am new to jquery so i am not sure if my function to clear should be inside my click function, or if it has to be outside of it. I'm seeing a lot of answers to this but they are not helping me. i have added a fiddle to give you just a idea of what i am trying to do. I shortened it to just give you a idea of what i am doing, so there maybe things wrong with it.
http://jsfiddle.net/46tYs/6/embedded/result/
$('.myOptions').change(function () {
$('.list').removeClass('active');
$('.' + this.value).addClass('active');
});
$('#butt').click(function () {
var ttta = $('.myOptions').val();
var tt = $('input[name=gender]:checked').val();
});
My html code:
<label>Please select an option :</label>
<select class="myOptions">
<option value="" selected>Pick an option</option>
<option value="owner">yes</option>
<option value="not-owner">no</option>
</select>
It seems unclear to me what your goal is. Judging by your reset button click code, it appears like you are having trouble removing "checked" and "selected" from radio buttons and drop downs? Here is the pertinent info:
"The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property:"
Here is the API docs explaining the difference:
http://api.jquery.com/attr/
http://api.jquery.com/prop/
Here is an example I wrote for you showing basics of getting values and resetting fields:
http://jsfiddle.net/SbB3k/
Here is a rewrite of your code, it's not optimized, but much better I think:
http://jsfiddle.net/46tYs/10/
of how to reset radio buttons and select options
Here is the gist of it:
$('input[type="radio"]').prop('checked', false).val("");
$('select').prop('selectedIndex',0);
$('input[type="text"]').val("");

Hide select option not reflecting

I am trying to hide some options from a select. The solution used is this:
this.selectBox.children(".myOption_"+optionValue).wrap("<span></span>");
this.selectBox is a jQuery object of the mentioned select.
In Firefox it works just fine, but in IE8 the changes are not reflected: if one should look at the select, it will seem unchanged. But if the user selects an option, the value respects the removed element.
Here is an example:
<option value="val1">Test1</option>
<option value="val2">Test2</option>
<option value="val3">Test3</option>
<option value="val4">Test4</option>
Now, when I select "Test1", a function is called and the above code is executed.
From the user's perspective, the options will remain the same. BUT if he now tries to select "Test1" again, the provided value will actually be "val2" and the option should be removed. Again, nothing happens, so he selects "Test1" again and the value will be "val3" and so on.
In order to display the occured changes, I have to hide and then show the select.
this.selectBox.children(".myOption_"+optionValue).wrap("<span></span>");
this.selectBox.hide().show();
The code above will make the changes visible(hide the clicked options).
What is more curious is that this fiddle:
http://fiddle.jshell.net/FAkEK/25/show/
works as it should on the same browser.
I do not understand why is this all of a sudden happening.
Why is this happening? Where should I look for the issue?
I am not sure why you would want to hide the option instead of removing it, but here's an example on how you can do it. It's based on this solution for hiding options.
Fiddle here -> http://jsfiddle.net/kAp42/2/
JSBin here (should work in IE8) -> http://jsbin.com/uyuram/1
var $select = $('select');
$select.prop('selectedIndex', -1); //ensure we can hide the first option
$select.change(function () {
//not sure why you would not want to remove the option instead of hiding it byt, if you want to hide...
$select.children('option:selected').wrap('<span class="hide-option"></span>');
//remove it
//$select.children('option:selected').remove();
this.selectedIndex = -1; //ensure we can hide the last option
});

Categories

Resources