I have a problem in which I have generated name of check box dynamically , which comes inside a loop, I have added loop id to the name and the name is generated for each row of the table (which is still the same ), I am trying to capture this variable in jquery , the expression comes fine but while running the code I am getting error "Uncaught Error: Syntax error, unrecognized expression:" , below is my Jquery code :
$('.select_all').on('click',function(){
var id = $(this).attr('id');
console.log("inside select all click id is :" + id)
var cbox = "'"+id+"checkBox"+"'";
var c ="\"input[name="+cbox+"]\"";
if($("#" + $(this).attr(id) + " INPUT[type='checkbox']").attr('checked', true)){
console.log("inside this");
$(c).each(function(){
console.log("inside ckbox")
this.checked = true;
});
}else{
$(c).each(function(){
this.checked = false;
});
}
});
here the variable c is formed like "input[name='1checkBox']" which is correct , but when it comes to the $(c).each part , it throws the above mentioned error. Can some let me know how the dynamic expressions are created and run in jquery . Thanks in advance.
You can try:
$(`input[name='${cbox}']`)
Example:
const name= "password"
console.log($(`input[name="${name}"]`)[0])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="password"/>
Ditch the redundant " marks enveloping the selector: instead of
var c ="\"input[name="+cbox+"]\"";
do simply
var c ="input[name="+cbox+"]";
I could resolve my issue by changing the code , below is the JS code which I used .
$('.select_all').on("click", function(event) {
console.log("inside event propogation")
event.stopPropagation();
});
$('.select_all').on('click',function(){
var id = $(this).attr('id');
var cbox = "'"+id+"checkBox"+"'";
if(this.checked) {
$("[name="+cbox+"]").each(function(){
this.checked = true;
});
}else {
$("[name="+cbox+"]").each(function(){
this.checked = false;
});
}
});
Related
I wish to pass 'selectlang' parameter in javascript and redirect to the MVC controller but the var 'selectlang' have error and mention that it does not exist in current content? Please guide me thanks!
My javascript:
$('.filterlang').on("click", function () {
var selectlang = document.getElementById("Language").value;
location.href = '#Url.Content("~/SURV_Main/SURV_Main_Details/?key=" + Model.Survey_Key +"&Language=" + selectlang)';
});
filterlang is button class and "Language" is dropdownlist id.
Have you tried this:
$(document).on(".filterLang", "click", function(){
var selectedLang = $("#Language").val(); // if it is normal dropdown, this will work for both cases
var selected2Lang = $("#Language").select2("val"); // if it is select2 dropdown
window.location = '#Url.Content("~/SURV_Main/SURV_Main_Details/?key=" + Model.Survey_Key +"&Language=' + selectlang + '")';
});
Hope this helps.
im about to develop a Formvalidator. I use a global Function which i call before every form-submit, i also give the form ID for accessing the inputs. so the function looks like this:
function FormValidation(formId)
{
var validated = true;
$("#" + formId ).each(function ()
{
var message="";
if ($(this).attr("data-validation-required") == "true" && $(this).val() == "") {
message += "-This field is required<br/>";
validated = false;
if (message != "")
$(this).after('<div class="popover fade bottom validation-error in" style="position:relative;display: block; margin-top:0px;"><div class="arrow" style="left:10% !important;"></div><div class="popover-content" style="color:#c0392b;">' + message + '</div></div>');
}
return validated; //true or false
}
so the problem is, that this each loop i wrote, is not accessing ALL children which are within the given "form" (by formId). Its accessing only the FIRST level children.
Here's some HTML example code:
<form id="myform">
<input type="text" data-validation-required="true"/> <-- will be accessed -->
<div class="SomeDivClass">
<input type="text" data-validation-required="true"/> <-- will NOT be accessed because 2nd level -->
</div>
</form>
<script>
$("#myform").submit(function(){
if(!FormValidation("myform"))
return false;
});
</script>
There are few issues in the given code
function FormValidation(formId) {
var validated = true;
//use descendant selector to find all required fields
$("#" + formId + ' [data-validation-required="true"]').each(function () {
//check whether the value is empty, if so mark as invalid
if ($(this).val() == "") {
var message = "-This field is required<br/>";
validated = false;
$(this).after('<div class="popover fade bottom validation-error in" style="position:relative;display: block; margin-top:0px;"><div class="arrow" style="left:10% !important;"></div><div class="popover-content" style="color:#c0392b;">' + message + '</div></div>');
} else {
//remove the validation of it is again become valid
$(this).next('.validation-error').remove()
}
//don't return the validated from the each loop since returning false here will cause the each loop to stop further iterations
})
return validated; //true or false
}
$("#myform").submit(function () {
if (!FormValidation("myform")) {
return false;
}
});
Demo: Fiddle
You could get all elements with data-validation-required via $('#' + formId +' [data-validation-required!=""]')
The jQuery API for traversing the DOM is incredibly well documented. To get all descendants of an element, you'd use .find(), along with a selector that didn't exclude anything — * — so your code would end up as follows:
$("#" + formId ).find( '*' ).each(function (){
But seeing as you're already creating a CSS selector to select the form, you may as well simply extend that selector:
$("#" + formId + " *").each(function (){
Your current form isn't even iterating the children — it's iterating over each form, and there's only one.
I have three text inputs :
First name
Last Name
User Name
In the form I have only these inputs are of type: text.
I want each one of them to be at least 4 characters long so I decided to validate them together.
I want to use Jquery to display an error message that is red when the length is less than 4 and green when it is greater.
I put three error messages respectively with the following Ids:
flength
llength
ulength
(the first letter corresponds to the input , example first name : flength and so on)
so here is my code to do this:
$('input [type= text]').keyup(function ({
var l = $(this).val();
var x = l.id;
x = x.charAt(0);
x = '#' + x + 'length';
if (l.length < 4) {
$(x).removeClass('valid').addClass('invalid');
} else {
$(x).removeClass('invalid').addClass('valid');
}
});
Why wouldn't this script work? what should I modify?
Edit
demo
After seeing your comments
changing var x = $(this).attr("id"); wont fix the problem too
since $(this).attr("id") gives your current element id and your current element is your input tag element and you did not set the id attribute, Instead you have set it to div tags as you have mentioned in your comments, since you are trying to retrieve id attribute which you have not set and your getting an error.
One solution I could give is this way
<input type="text" name="flength"/> // set name attribute same as div ids
<input type="text" name="llength"/>
<input type="text" name="ulength"/>
$('input[type=text]').keyup(function ({
var l = $(this).val(); // get the input string
var x = $(this).attr('name'); // get the current input element name attribute
if (l.length < 4) {
$('#' + x).removeClass('valid').addClass('invalid');
} else {
$('#' + x).removeClass('invalid').addClass('valid');
}
});
Check this http://jsfiddle.net/Q2y8m/4/
Try this
$(document).ready(function () {
$('input[type=text]').keyup(function () {
var l = $(this).val();
var x = $(this).attr('id'); // notice it is not l.id
x = x.charAt(0);
x = '#' + x + 'length';
if (l.length < 4) {
$(x).removeClass('valid').addClass('invalid');
} else {
$(x).removeClass('invalid').addClass('valid');
}
});
});
Demo http://jsfiddle.net/3yqVg/2/
Try to change var x = l.id; width var x = $(this).id;
I have a following html string of contentString:
var content =
'<div id="content">' +
'<div>' +
'<input name="tBox" id="select" type="checkbox" value="" '+
'onclick="changeView()"> Select for operation' +
'<p style="text-align:right">View details</p>' +
'</div>' +
'</div>';
Here, How I find the checkbox select by id and add attribute checked on changeView() function?
function changeView(m) {
//find the select id from content string
var checkbox = content.find($('#select'+m));
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Thanks in advance.
If you convert it to a JQuery object first then you can do it like this:
var contentObj = $(content);
var checkbox = contentObj.find("#select");
checkbox.attr("checked", true);
then if you need it back at html string:
content = contentObj[0].outerHTML;
Note: If outerHTML is not working as expected, the following JQuery can be used as an alternative:
content = contentObj.clone().wrap('<div>').parent().html();
If m is meant to be the id you want to find (e.g. "select"), then use this:
var checkbox = contentObj.find("#" + m);
Live Example: Here is a working example
Here is the complete function for easy reference:
function changeView(m) {
var contentObj = $(content);
var checkbox = contentObj.find("#" + m);
checkbox.attr("checked", true);
content = contentObj[0].outerHTML;
}
You need to compile the string into a DOM object first by wrapping it in a jQuery call first. Then you can use the find method.
So:
var dom = $(content),
select = dom.find('#select');
In any case, there is no need to add the 'checked' attribute, because when you click the checkbox, it will automatically become checked.
If however, you want to still programmatically check it:
select.on('click', function () {
this.attr('checked', 'checked');
});
Simply like this
function changeView(m) {
//find the select id from content string
var checkbox = content.find('#select');
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
if you want to pass id then
function changeView(m) {
//find the select id from content string
var checkbox = content.find("#" + m);
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Since you're using the onclick handler, you don't really need to do any of that :
in html : onclick="changeView(this);"
function changeView(box) {
if(box.checked) { stuff; }
// or get jquery ref to that box :
$(box).prop("checked", true);
}
I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.