Generating id selector dynamically based on user-input - javascript

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.

Related

jQuery selector for data attribute array

Theres' this html code:
<div class="wcpa_form_outer" data-attrrelated="["wcpa-select-1658734650073"]">
for which i'm trying to append html to it. I have tried various approaches but none have worked.
jQuery('.wcpa_form_outer[data-attrrelated="["wcpa-select-1658734650073"]"]').append('some html here');
or
jQuery('.wcpa_form_outer[data-attrrelated="[wcpa-select-1658734650073]"]').append('some html here');
or
jQuery('.wcpa_form_outer').data('attrrelated').append('some html here');
any clues?
The " and/or [] in the attribute value may be the problem Remove it, or try using a part (the most relevant part?) of the attribute value:
$('[data-attrrelated*="1658734650073"]')
.append('some html here!');
$('[data-attrrelated*="wcpa-select-165873465007"')
.append('<br>some html here too!');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wcpa_form_outer" data-attrrelated="["wcpa-select-1658734650073"]"></div>
Problem is that you're using the HTML Entity " in your attribute. This is being translated to a literal quote. JQuery does not do Entity translation, so it's literally looking for the string ["wcpa-select-1658734650073"] with ampersands and all, not ["wcpa-select-1658734650073"] which is the actual value in your attribute.
You can work around this by using one of the following methods (after also translating the Entity into a quote in your code).
Use a CSS "contains" selector for your attribute ( attr*=value ) (demonstrated by KooiInc's answer) or
Use a string template which will allow you to embed both types of quotes in your string and get an exact match ( attr=value ), shown below
Constructing a string value containing quotes by using string concatenation (e.g. '["' + value + '"]' )
Use the decodeEntities function from this answer to translate your attribute value before attempting the lookup (untested, and it's 10 years old)
jQuery(`.wcpa_form_outer[data-attrrelated='["wcpa-select-1658734650073"]']`).append('foo')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wcpa_form_outer" data-attrrelated="["wcpa-select-1658734650073"]">append here:
</div>

Escaping forward slash ("/") while using JavaScript to change CSS class

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');

Jquery, Escaping url with variable

trying to escape and html for appending in jquery with adding a dynamic variable that i am bringing in with ajax and I seem to not be able to get the escaping correct. Here is what I have -
$("<div><div class='presiImg' style='background: url(/\'/gleam\/public\/images\/itPrecedents\/" + keep.logo + "');'></div></div>").appendTo(".myDiv');
I am unsure how to escape this correctly so I can use the variable. Thanks.
You've got a couple issues here:
You're escaping the forward slashes in your URL and that is not necessary
You are using inconsistent quotes in your .appendTo()
As a suggestion, when I append raw HTML using JS/jQuery I try to use the single-quote and the JavaScript quote, and then use the double-quotes in the HTML. For me it is just easier to see that way. Also, the single-quote in the CSS url is not required, and is perhaps confusing the matter.
Anyway, if you change your line to the following it will work:
$('<div><div class="presiImg" style="background: url(\'/gleam/public/images/itPrecedents/' + keep.logo + '\');"></div></div>').appendTo('.myDiv');
There is a runnable example below if you want to see it in action:
$(function() {
var keep = { logo : "test.jpg" };
$('<div><div class="presiImg" style="background: url(\'/gleam/public/images/itPrecedents/' + keep.logo + '\');"></div></div>').appendTo('.myDiv');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myDiv"></div>
try
$("<div />",{
"class":"presiImg",
"style":"background: url(/gleam/public/images/itPrecedents/"+keep.logo+")"
}).appendTo(".myDiv");

jQuery select input elements in a target form with a certain class

I have several forms in one page, and I wanted to target all input fields in a target form (form ID) that has a certain class in it (Eg."has-error" ).
I though this would do the trick:
target_elem = "#form_b";
$(target_elem + ":input").hasClass("has-error").removeClass("has-error");
No luck so far. I've tried playing w/ filtering as well. tsk
Demo
Simply Use .class selector:
$(target_elem + " input.has-error").removeClass("has-error");
Try this , Let me know if it helps :
$(".has-error").each(function(){
$(this).removeClass("has-error");
});
Live example : http://jsbin.com/yudaseqe/1/edit
No need to use ':'
$(target_elem + " input").hasClass("has-error").removeClass("has-error"); should work
Note that you also can forget about hasClass("has-error")
It will take more time to find input with this class than deleting this class of every input without checking if it exists.
target_elem = "#form_b";
$(target_elem + " input").removeClass("has-error");
try this...
$("input[class*='has-error']",$(target_elem)).removeClass("has-error");
Or use this
$("input.has-error",$(target_elem)).removeClass("has-error");

Setting the value of a hidden input

The idea: I'm setting the value of an input with type="hidden" via regular Javascript or jQuery.
The issue: neither jQuery nor document.getElementById will find the hidden input, even though I'm absolutely sure the selector is correct and there are no conflicting elements.
The code:
I can't really post much of it, because it's full of rather complicated PHP that confuses me when I just look at it.
Here's the javascript:
$("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);
Note: there's nothing wrong with the selector, and the "input" is a different element that I'm using to reference the hidden.
Here's the HTML:
<input type="hidden" name="s<?=$step_counter?>_budget_hidden"
id="s<?=$step_counter?>_budget_hidden" value="0" />
The code is kind of out of context, but it's more of a general problem with Javascript than a syntactical error. Thoughts?
In $("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total); you take two chars before the first underscore in your hidden id. However your hidden id have only one char 's'
EDIT
Ok the <?= ?> was hidden before the question edit.
Do you call your script after the body onload event?
EX:
$(document).ready(function(){
$("#" + input.id.substr(0,2) + "_budget_hidden").bind("keyPressed",function(){
$("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);
}
});
FYI: We can get the hidden input value using jQuery, even we can also edit any hidden input value using jQuery.
I think your way of getting the hidden value using 'substr' method is causing some problem. You are using like substr(0, 2) so are sure that the variable $step_variable is a single digit number, otherwise your code will not return correct result.
I am giving some sample code below, check it once.
Here's the javascript:
var input_id = $("hidden_val").attr("id").substr(1);
$("#" + input_id + "_budget_hidden").val(budg_total);
Here's the HTML:
input type="hidden" class="hidden_val" name="s_budget_hidden" id="s" value="0"
I think this will help you. Let me know if you are not following this flow to solve your issue.
I think that input.id.substr(0,2) says to start at the start of the string, take 2 characters and use that.
http://www.w3schools.com/jsref/jsref_substr.asp
Try using Firebug to see what the result of that method call is.

Categories