Preserve a value of an element after change using jQuery - javascript

For internationalization support, I wrote code that changes the URL from #lang-select dropdown .The code is
$(document).ready(function(){
var sel = document.getElementById('lang-select');
sel.onchange = function(){window.location.replace($('#lang-select').val());};
});
the above code works fine and it changes the URL from http://0.0.0.0:3000/fr to http://0.0.0.0:3000/en.
Now I want to preserve the changed value, but without success. I have written the code below. I don't know why it is wrong/not working .
function langSelect(){
var available_languages = {
"en":"English",
"de":"Deutsch",
"ru" :"Россию",
"fr" : "Française"
};
var languageInUrl= document.URL.split("/")[3];
for(var shortLanguage in available_languages){
if(shortLanguage === languageInUrl) {
var langaugeOptionArray = $("#lang-select>option");
for(var i = 0 ; langaugeOptionArray.length > i ; i++){
if(langaugeOptionArray[i].label === available_languages[shortLanguage]){
langaugeOptionArray[i].selected = true;
return;
}
}
}
}
}
Please tell me what's wrong in above code and since what I am doing is not a new thing, please share what is the best practice to overcome this scenario.
Currently, I am using backend to accomplish this.

$(function() {
$('#lang-select').on("change",function(){
window.location.replace($(this).val());
});
});
function langSelect(){
var available_languages = {
"en":"English",
"de":"Deutsch",
"ru" :"Россию",
"fr" : "Française"
};
var languageInUrl= document.URL.split("/")[3];
var lang = available_languages[languageInUrl];
if (lang) {
var langaugeOptionArray = $("#lang-select>option");
langaugeOptionArray.each(function() {
if($(this).text() === lang){
$("#lang-select").val(lang);
return false;
}
});
}
}
I believe we can even do
if (lang) {
var opt = $("#lang-select").find('option[text="'+lang+'"]').val();
if (opt) $("#lang-select").val(opt);
}
Good luck

Related

unable to get property 'style' of undefined or null reference for background colour

Hi I'm getting script error for below code. as I tried all the ways but no luck .
kindly help me as I'm very new to this field. atleast tell me where am I going wrong
<body onload="hightlightMoreLink(2210);hightlightMoreLink(2211);">
function hightlightMoreLink(groupID) {
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID)       var moreLinkColumnElement = "";
var moreLinkElement = "";
if (groupID == 2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");        
moreLinkElement = document.getElementById("labelingMoreLink");
} else { 
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color = "#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
(getting error on this line)
moreLinkElement.style.color = "#26339f";
}
}
Here it is working...
function hightlightMoreLink(groupID) {
var isHightlightRequired = 1
var moreLinkColumnElement="";
var moreLinkElement="";
if (groupID==2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");
moreLinkElement = document.getElementById("labelingMoreLink");
} else {
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color="#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
moreLinkElement.style.color="#26339f";
}
}
hightlightMoreLink(2210)
First of all, you should create a fiddle so people can better understand the problem.
Checking your code though, I think the problem is in this line:
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID)
Check if it is return a boolean.
Aside from that, I think you should work with classes to manipulate the elements' styles. The onload you're putting on the body is not a good practice either. Jquery has a function for that purpose.
$( document ).ready(){
hightlightMoreLink(2210);
}
Another thing I would point out is the fact that you could use jquery to manipulate the elements. As is:
$("#MoreLinkTH").css("background-color", "#26339f");
$("#labelingMoreLink").css("color", "#fff");

How to optimize this javascript duplicates

I wrote this code, but since I'm just starting to learn JS, can't figure out the best way to optimize this code. So made a duplicates for every if statement.
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$('.lang').hide();
$('.lang-all').click(function(){
$('.lang-all').hide();
$('.lang').slideToggle(200);
});
} else {
$('.lang').show();
$('.lang-all').hide();
}
if(gender.length == gender.filter(":checked").length){
$('.gender').hide();
$('.gender-all').click(function(){
$('.gender-all').hide();
$('.gender').slideToggle(200);
});
} else {
$('.gender').show();
$('.gender-all').hide();
}
});
So this is my code, as you can see on line 15 if(gender... I have a duplicate of previous code, just changed variable from "lang" to "gender". Since I have more that two variables, I don't want to make duplicate of code for every each of them, so I hope there is a solution to optimize it.
You can write a function to let your code more abstract, see:
function isChecked(obj, jq1, jq2){
if(obj.length == obj.filter(":checked").length){
jq1.hide();
jq2.click(function(){
jq2.hide();
jq1.slideToggle(200);
});
} else {
jq1.show();
jq2.hide();
}
}
//Your jQuery code, more abstract
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
isChecked(lang, $('.lang'), $('.lang-all'));
isChecked(gender, $('.gender'), $('.gender-all'));
});
make a function which had similar functionality, then pass a parameter as a class or id
$(function() {
call('.lang');
call('.gender');
function call(langp){
var lang = $(langp+" input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$(langp).hide();
$(langp+'-all').click(function(){
$(langp+'-all').hide();
$(langp).slideToggle(200);
});
} else {
$(langp).show();
$(langp+'-all').hide();
}
}
});

Update attribute data-id for li element Nestable don't update

I has problem with Nestable.
When i use
var updateOutput = function (e) {
var list = e.length ? e : $(e.target),
output = list.data('output');
if (window.JSON) {
output.val(window.JSON.stringify(list.nestable('serialize'))); //, null, 2));
} else {
output.val('JSON browser support required for this demo.');
}
};
$('#element').attr({'data-id':'newvalue'});
updateOutput($('.nestable').data('output', $('#nestable_list_output')));
I don't see output change. When i view our via chrome i see data-id of that element changed.
Please help me.
This is full soure
function Update_This_Menu(){
$('.update-this-menu').click(function(){
var RootElement = $(this).parent().parent().parent();
var NameMenu = RootElement.find('.NameThisMenu').val();
var TitleMenu = RootElement.find('.TitleThisMenu').val();
if(NameMenu == ''){
RootElement.find('.NameThisMenu').addClass('parsley-error');
}
else {
RootElement.data({'name':NameMenu});
RootElement.data({'title':TitleMenu});
updateOutput($('.nestable').data('output', $('#nestable_list_output')));
RootElement.find('.form-edit-menu').hide('slow');
}
});
}
This is function remove MENU is OK
function Remove_Menu(){
$('.remove-this-menu').click(function(){
var RootElement = $(this).parent().parent().parent();
RootElement.remove();
updateOutput($('.nestable').data('output', $('#nestable_list_output')));
});
}
Sorry for my english
Try this:
$('#element').data('id','newvalue');

Hide div with js, but without affecting html code

Let's say we have a div with id = '123'
Ho to make it invisible with js without affecting its html code?
So document.getElementById('123').style.display = 'none' is not an option.
JS only
UPD:
I just have interesting task! I have to hide some comments with js from guestbook , but when I change html code to hide it, Server somehow understands what I've done and redirects me to warning Page. So I have to do something with that.
UPD2:
I had obfuscated script on my page
function check_divs() {
var try_again = true;
var arr_divs = document.getElementById('content').getElementsByTagName('div');
if (arr_divs.length != divs_count) {
try_again = false;
} else {
for (var i = 0; i < arr_divs.length; i++) {
if ((arr_divs[i].style.display == 'none') || (arr_divs[i].style.position == 'absolute')) {
try_again = false;
};
};
}; if (try_again) {
setTimeout(check_divs, 998);
} else {
document.location.href = '/alert.html';
};
}
This one, so my solution was to clear all timeouts.
document.getElementById('123').style.visibility = 'hidden';
or
document.getElementById('123').setAttribute('style','display:none');
or
document.getElementById('123').setAttribute('style','visibility:hidden');
or if you have jQuery libraries
$('#123').css('visibility','hidden')
or
$('#123').css('display','none')
Any of that help?

Using $_GET with Jquery

I currently have the following code on my website:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
I would like to have an if(isset($_GET['email')); trigger this function as well, so have it open on page load if the $_GET variable is set.
I'm rather new with Jquery and not sure if this is possible, I also have another somewhat related question, I'm not sure if I should make a new question for this as I'm fairly new to stackoverflow as well, but here it is.
Say I have two of these:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
$(document).ready(function() {
$("#archivestop").on("click", function(e)
{
e.preventDefault();
$("#archives").toggle('fast');
});
});
I want one to close if the other one is opened, how would I go about this?
Thanks!
Here's the Javascript-solution:
function getParam(key) {
var paramsStr = window.location.search.substr(1, window.location.search.length),
paramsArr = paramsStr.split("&"),
items = [];
for (var i = 0; i < paramsArr.length; i++) {
items[paramsArr[i].split("=")[0]] = paramsArr[i].split("=")[1];
}
if (key != "" && key != undefined) {
// return single
if (items[key] != undefined) {
return items[key];
} else {
return null;
}
} else {
// return all (array)
return items;
}
};
if (getParam("email")) {
// ...
}
Regarding your second question you can use the following to determine if an element is visible:
var bool = $('.foo').is(":visible");
So to hide an element if it is visible you would do something like this:
if ($('.foo').is(":visible")) {
$('.foo').hide();
}
I'm silly and have answered my first question. I still have yet to have my coffee.
The following works, just insert it into the div that is to be displayed:
<div id="contactform" style="<?php if(isset($_POST['email'])) echo "display:block;" ?>">
content
</div>

Categories

Resources