I need to add some CSS class based on some condition using JavaScript but facing issue in case my string contains a forward slash (/). This is what my use case is
<div id="div_product-size-icon-121NM/L" class="disabled"></div>
<script>
var newProductCode = '121NM/L';
if( newProductCode.contains('/') ){
newProductCode = newProductCode.replace('/','/\//');
$('#'+'div_product-size-icon-'+newProductCode).addClass('active');
}
</script>
I have even tried newProductCode.replace('/','/\'); but while running code, I am facing following error
JavaScript error: SyntaxError: unterminated string literal
I can not change HTML along with product code; the option for me is to change it in JS.
Here is a working js example: JS code
I have first replaced the if statement with indexOf() and changed the .replace function as .replace('/', '\\/');
var newProductCode = '121NM/L';
if (newProductCode.indexOf('/') > 0) {
alert('Once you click OK, the text will disappear!!');
newProductCode = newProductCode.replace('/', '\\/');
$('#' + 'div_product-size-icon-' + newProductCode).addClass('active');
}
div.active {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_product-size-icon-121NM/L" class="disabled">Some text here</div>
#Pugazh probably has the correct way of doing it, but you could just isolate the string in " by searching using an attribute in jQuery. Here's a link to the API documentation. It avoids having to do the replace altogether. It's a hacky way of doing it.
var newProductCode = '121NM/L';
$('[id="div_product-size-icon-'+newProductCode+'"]').addClass('active');
Related
I am facing a problem in jQuery selector. I am generating selector string dynamically based on user-input as show below :-
jQuery("#" + userInput + "-edit").modal("show")
When the user enters value like "AdvancedResults." Selector becomes
jQuery("#AdvancedResults.-edit").modal("show")
which does not return expected element, despite the fact that
Am I doing something patchy ? Is there any better way to solve this problem ?
Btw, apologising for newbie question, as I am new to JS world.
Thanks in advance.
Just use:
Use the escaping rules from the jQuery selectors API as follows:
$("#AdvancedResults\\.-edit").modal("show");
You can replace . to \. dynamically using str.replace():
var str = "AdvancedResults.";
str = str.replace(/\./g, "\\."); // it will add add \\ dynamically before .
console.log($("#"+str+'-edit').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input id="AdvancedResults.-edit" type="text"/>
If your element does have an id #AdvancedResults.-edit, that is, includes a dot, you must escape it with \\ as stated in the docs jQuery Selectors
Use [attribute=""] selector in such cases where the parameter is dynamic and might contain special chars not supports by jQuery # - ID selector.
jQuery("[id='" + userInput + "-edit']").modal("show")
Example snippet :
var userInput = "abc.";
alert(jQuery("[id='" + userInput + "-edit']").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="abc.-edit" value="test"/>
I have solved it using attribute hack.
It's as follow :-
jQuery("[id='" + userInput + "-edit']").modal("show");
It worked perfectly for me.
I am trying to append a new list item based on a condition using jquery. For reference the page is a Wordpress page and i have been able to implement serval jquery scripts using same format.
Here is the sample HTML.
<div class = "bag" id = "bag" style="width: 100%; padding: 0 0 0 5px; float: left;">
<ul id = "clubsli" name = "clubsli" class = "clubsli">
I dynamically create a li with "n" values and want to append a new li to the end of this list using JavaScript/jQuery script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
function addClub() {
$roleint = 2613;
$count = $("#clubsli li").length - 1;
if ($roleint == 2613) {
if ($count < 100) {
$("#bag ul").append('<li>$roleinit</li>');
};
};
};
});
</script>
No matter what I do I get the following Unexpected token ILLEGAL error that seems to not like the "<" in the list element.
Here is the error I receive.
I've tried appending a non-li and can without fail and tried "appendTo" but get same error on the "<".
Your code is basically okay. Here's a working JSFiddle version of it, with the following problems or incompletenesses corrected:
$(document).ready(function () {
function addClub() {
$roleint = 2613;
$count = $("#clubsli li").length - 1;
if ($roleint == 2613) {
if ($count < 100) {
$("#bag ul").append('<li>' + $roleint + '</li>');
};
};
};
addClub();
});
You needed to use the string appending operator + in your appended string.
You'd typo'd $roleint as $roleinit in your append()
You'd declared the addClub() function, but not actually called it. I presume it was being called somewhere else in your code?
In addition, as Guido points out, it's quite odd to use variable names starting with $ in jQuery unless the variable is actually a jQuery object, so that makes your code read quite strangely.
I don't think any of this would have caused the error in your question, though, so perhaps there's something else going on that we can't see from your description?
Problem solved! Similar post on WordPress specific stackexchange shows how to edit functions.php so WP does not auto-insert page breaks.
https://wordpress.stackexchange.com/questions/101368/wordspress-add-p-into-my-javascripts
Thanks to those that helped clarify what was causing the problem for me. Gave me better idea on where to look.
I want to change the design of my site by changing the CSS file attached. I have tried with script when the link is with id "link"
var x = document.getElementByID ("link")
X.href = style2
It didn't work.
The other thing I tried was to hide the <link> tag which had class "linkclass"
<style>
link.linkclass {
visibility:hidden;
}
</style>
But it didn't work either.
Can someone help.
Sorry if the code is bad formatted but I can't get how to format code in stack overflow
Three things wrong with this:
javascript is case sensitive. That means X is a different variable than x
style2 is not a valid URL. You have to use an URL to an existing .css file
<link> is not a visible element. Hiding an element that isn't visible in the first place accomplishes nothing.
This works:
var x = document.getElementByID("link");
x.href = "http://url/to/your/style2.css";
// ^ notice the lowercase x
If you wanna hide element (I got that impression from your examples), your javascript code should look like this:
var x = document.getElementById("link");
x.style.display = 'none';
Also take care with following:
-uppercase letters getElementbyId
-you're missing semicolon (;) after first expression
-your variable "x" is uppercase in second row("X").
In most cases this should be enough to disable element with CSS, just add this class (linkclass) to element which you want to hide:
<style>
.linkclass {
display: none;
}
</style>
You could do
$("#link").disabled = true;
This may also work.
document.getElementByID("link").disabled = true;
There is also another Stack question that addresses this here. Removing or Replacing a Stykesheet
update
You say you are trying to change the stylesheet. You could create a function to do it like this.
function styleSheetSwitcher( newFile ){
$("#link").prop("href", newFile);
}
styleSheetSwitcher("myNewCss.css");
I have little html experience and no java experience and am trying to display an SVG image once the option is selected. Currently the code is at this, which displays a gif image:
<SELECT NAME=SIGN_NFPA onchange=\"
this.form.SIGN_PIC1.selectedIndex = 0;
var id = this.options[this.selectedIndex].value
var lnk = (id) ? 'SignNFPA/'+id+'.gif' : 'images/blank.gif';
window.document.SIGN_PIC1.src = lnk;
return true;
\">
Now we are generating files and want to replace that with this line of code
<SELECT NAME=SIGN_NFPA onchange='$("img[name=SIGN_PIC1]").prop('src',"SignNFPA?nfpa="+this.value);'>
but I keep getting a syntax error, what am I doing wrong? I know it should be a function in onchange but my coworker says you can input code directly instead. Thanks.
Your immediate problem is nested single-quotes around "src". This is causing it to see onchange='$("img[name=SIGN_PIC1]").prop(' as a complete attribute, followed by garbage.
Change those to be a compatible set of quotes:
<SELECT NAME=SIGN_NFPA onchange='$("img[name=SIGN_PIC1]").prop("src","SignNFPA?nfpa="+this.value);'>
but this would read as more "standard" like this:
<SELECT NAME="SIGN_NFPA" onchange="$('img[name=SIGN_PIC1]').prop('src','SignNFPA?nfpa='+this.value);">
But as your are using jQuery, I would strongly suggest moving to using a jQuery event handler, and appropriate data- attributes and not use a inline handler.
e.g. something like the following (not checked for errors - just a guide)
HTML:
<SELECT NAME="SIGN_NFPA" \>
jQuery
$(function(){
$('[name="SIGN_NFPA"]').change(function(e){
var $signpic1 = $('[name="SIGN_PIC1"]')
$signpic1.val(0);
var id = $(this).val();
var lnk = (id) ? 'SignNFPA/'+id+'.gif' : 'images/blank.gif';
$signpic1.attr("src", lnk);
});
});
Use quotes when adding attributes in HTML. Specially in value
<select name="SIGN_NFPA">
<!--options-->
</select>
Using event Handler in jquery
$(document).ready(function() {
$("select[name='SIGN_NFPA']").change(function() {
$('img[name=SIGN_PIC1]').prop('src', 'SignNFPA?nfpa=' + this.value);
})
});
Turned out it was because I was in quote hell, probably should've mentioned that but I'm relatively new to programming. I'm in a perl file using html thats using jquery and the $ sign was being interpreted as a scalar, causing a syntax error. Also simultaneously in quote hell
Hello I have a function that loops around and then eventually a string gets sent to a DIV tag class...
$(document).ready(function addcopy() {
/* global */
$(".Bands").append('<div style="display: inline-block;">[EDIT] <h7 style="color:#7A0029;line-height: 110%;text-transform: uppercase;">[Custom:Name]</h7> </div>');
});
It works fine... however the token [Custom:Name] may contain special characters such as single or double quotes etc...
I've looked around these forums and tried to adapt my code to various solutions offered and it never seems to work, could somebody help me?
Thanks for your help!
Alex
EDIT(1):
Getting somewhere, from Ockert's and LeFex's answer I've adapted it below but it still does not work (replace speech marks and special characters from token which html can't handle)...
function htmlEncode(value){
return $('<div/>').text(value).html();
}
$(document).ready(function (){
/* global */
var band = $("<div style='display: inline-block;'>[EDIT] <a href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.appendTo(htmlEncode('.Bands'))
});
You can change your script too
$(document).ready(function (){
var band = $("<div style='display: inline-block;'>[EDIT] <a class='link' href='[LINK]'><h7 class='name' style='color:#7A0029;line-height: 110%;text-transform: uppercase;'>[Custom:Name]</h7></a> </div>");
band.find('.name').html("some weird name !##$%^&*");
band.find('.link').attr("href","http://www.google.com");
band.appendTo('.Bands');
});
By splitting it up like that, enables you to set the name to anything you want. You can easily select the name element
Have a look at this jsfiddle http://jsfiddle.net/fL3gn056/2/
You could use document.createElement instead of just appending a string.
http://www.w3schools.com/jsref/met_document_createelement.asp
If you just create your div, a and h7-elements, use the appendChild function, and add style and attributes and content by setting element properties, you should end up with a sollution that allows any special characters.
Edit:
I could'nt get it working using that method; however, with the approach I suggested above, i got some working code:
var element = document.createElement("div");
element.style.display = "inline-block";
var link = document.createElement("a");
link.setAttribute('href', "[LINK]");
var text = document.createElement("h7");
text.style.color = "#7A0029";
text.style.lineHeight = "110%";
text.style.textTransform = "uppercase";
text.innerHTML = "[CUSTOM:NAME]";
//not sure what you're appending it all to, but do it here
document.getElementsByClassName("Bands")[0].appendChild(element);
element.appendChild(link);
link.appendChild(text);
With this snippet, all input special characters are interpreted as a string, not as code. Some calls I could have put in the same line, but this way you get an easy to read overview.
Here's an earlier thread on the subject, and the top answer brings the issue of performance of different approaches to discussion.
jQuery document.createElement equivalent?