October 8, 2013

Using .on() and targeting elements with a specific ID

Brandon Durham’s Question:

I understand you can use .on() to attach a single click event to an element and then specify which child elements receive the click. So, for example:

$(this.el).on("click", "span", function () {
    alert("Bloop!");
});

I need to be a bit more specific and target selectors with a particular attribute, like this:

$(this.el).on("click", "span[data-placeholder]", function () {
    alert("Bloop!");
});

That doesn’t seem to work, though. As soon as I add the attribute it stops working. No errors, just doesn’t seem to find the elements.

Is that the expected behavior? Is there a way around it?

CLARITY

$(this.el) is just a div that contains a number of elements, some of which are <span data-placeholder="First Name"></span> tags. There could be dozens of those <span> tags and I didn’t want that many event listeners, so I thought I’d use .on() to add the click to the parent container.

You can choose to filter your spans

$('span', this.el).filter(function() {
     return $(this).hasAttr('data-placeholder');
}).on('click', function() {
   //This is for all the spans having data-placeholder
   //...
});

Or if the placeholder is set via data api:

$(this.el).filter(function() {
     return $(this).data('placeholder') != 'undefined';
}).on('click', function() {
   //This is for all the spans having data-placeholder
   //...
});

This functions above select those elements specifically, if event delegation on the OP is needed, then you can do the following:

$('span', this.el).on('click', 'span', function() {
     if($(this).data('placeholder') != 'undefined') {
         alert('bloop');
     }
});
September 12, 2012

jquery nth selector in IE7

Question by Phil

I have a list of elements and need to make some amends to the first element in the list using jquery. I have tried a few methods to target the first item but none of them seem to work in IE7. These are the following methods I’ve tried…

 $(this).eq(1)
 $(this).first()
 $(this:nth-child(1))

All of these methods worked in all browsers except IE7, does anyone know of a fix to use for IE7 or a different method that will work in IE7?

Thanks in advance for any help?

Answer by Pradeeshnarayan

Try like this

$(this:first-child)

Will get more info from here

EDIT

Sorry for the confusion.
What I was trying to say is to use first-child instead of first()

You can use like this $('ul li:first-child').css('background-color', 'red');

Answer by Starx

.first() is a valid function and will work.

For example:

$("li").first(); // will match the first li in the tree
May 16, 2012

Jquery, get label value inside a user control

Question by LuisEValencia

I need to make a calculation in an asp.net page with the value from a usercontrol label.

the user control label is:

 <asp:Label ID="LblInvoicePriceValue" runat="server" ></asp:Label>

I include it like this:

<Controls:VehicleInformation ID="VehicleInformationControl" runat="server" />

And my jquery function is something like:
Please see point 1 and 2.

<script type="text/javascript">
        $(document).ready(function () {
            alert('call function to do calculation here');
            // 1.   Find in the vehicle information user control the invoiced ammount label
            // 2.   Find the vat excluded value **after** it was typed in the textbox
            // 3.   If invoiced ammount is greater than zero, then
            // 3.a  Find Label Percentage 
            // 3.b  Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
        });
  </script>

HTML generated:UPdate1

For the label:

 <span id="MainContent_VehicleInformationControl_LblInvoicePriceValue" class="bold"></span>

For the textbox:

<input name="ctl00$MainContent$TxtVatExcluded" type="text" id="TxtVatExcluded" class="calculation" />

Update 2:

<script type="text/javascript">
        $(document).ready(function () {
            alert('call function to do calculation here');

            $("#TxtVatExcluded").keypress(function() {
                var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
                var vatexcluced = $("#TxtVatExcluded").val();
                var lblPercentage = $("#MainContent_LblPercentage");
                if (invoiceprice > 0) {
                    lblPercentage.text((vatexcluced / invoiceprice) * 100);
                }
            })

            // 1.   Find in the vehicle information user control the invoiced ammount label
            // 2.   Find the vat excluded value after it was typed in the textbox
            // 3.   If invoiced ammount is greater than zero, then
            // 3.a  Find Label Percentage 
            // 3.b  Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
        });
  </script>

Answer by Imdad

var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
$("#TxtVatExcluded").val(label_text);

UPDATE
If you want to check if the textfield is blank then only do copy the label then use following code

var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var txt = $("#TxtVatExcluded").val();
if(txt.length==0)
{
  $("#TxtVatExcluded").val(label_text);
}

Answer by Starx

You can use the rendered ID of the elements to get the values using jQuery

var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();

Later when the calculation is complet, you can update the label text as

$("#MainContent_VehicleInformationControl_LblInvoicePriceValue").html("new label");

Update:

To use the logic, where the user types, you have to bind the function to keypress/keyup/keydown event

$("#myinputbox").keypress(function() {
    var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
    var tbox = $("#TxtVatExcluded").val();
    //... so on
}

Update 2:

Since, you are attempting to calculate with the values, it is safer to make sure, there are numbers in the first place. For that, you can use parseInt(), parseFloat() as needed.

        $("#TxtVatExcluded").keypress(function() {
            var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
            var vatexcluced = $("#TxtVatExcluded").val();
            var lblPercentage = $("#MainContent_LblPercentage");
            if (invoiceprice > 0) {
                lblPercentage.text((parseInt(vatexcluced) / parseInt(invoiceprice)) * 100);
            }
        })
May 5, 2012

Jquery contains selector, regex

Question by Jernej Pangeršič

This is my code:
Let’s say that name is set to john

$("#first_table").append($('#second_table').find("tr:contains(" + name + ")"));

Basically I have 2 tables on my website. I would like to move elements from first to second, but only if they match completely. How can i do that?

Now if I have (for example) john john #1, john #2 in my table, they would all be moved. I would only like to move john and leave john #1 and john #2
Thanks!
EDIT:
I would like the code to work to match the variable name EXACTLY.
So if name is JOHN it must only get JOHN. If it’s JOHN #1, it must only get JOHN #1 and so on. Is this possible?

Answer by Starx

Since every name case is valid to :contains(" + name +") statement, it matches all of them.

Try this, with a :not to omit the one with “#”

$("#first_table").append($('#second_table').find("tr:contains(" + name + "):not(:contains('#'))"));

Update:

If you want to be precise about the values inside. Then use something like this

$("#second_table tr td").each(function() {
   if($(this).text() == 'John') { 
     $(this).closest("tr").appendto($("#first_table")); //find the cotaining tr and append to another table
   }
});
April 23, 2012

jquery ul li selector

Question by lucky13

I have this list

<ul style="display:none">
  <li id="key1" title="Look, a tool tip!">item1 with key and tooltip
  <li id="key2" class="selected">item2: selected on init
  <li id="key3" class="folder">Folder with some children
    <ul>
      <li id="key3.1">Sub-item 3.1
      <li id="key3.2">Sub-item 3.2
    </ul>

  <li id="key4" class="expanded">Document with some children (expanded on init)
    <ul>
      <li id="key4.1">Sub-item 4.1
      <li id="key4.2">Sub-item 4.2
    </ul>
</ul>

Is there any way to select each < li > by its “id” with query?

Ive tryed it like this but its now working

$("ul li:#key1").qtip({
         content: '<img src="icons/Icon.png" />'
    });

Thanx for the answers but none of the above was working.. Ive tryed this

$("ul li:first").qtip({
 content: '<img src="icons/Icon.png" />'
});

and im able to see the qtip.But only for the first on the list (key1).
Trying

$("ul li#key1").qtip({
 content: '<img src="icons/Icon.png" />'
});

or

$("#key1").qtip({
 content: '<img src="icons/Icon.png" />'
});

its not working for me.. =/

Answer by Starx

Why the extra colon :? You dont need it.

$("ul li#key1").qtip({
     content: '<img src="icons/Icon.png" />'
});
April 2, 2012

Use jQuery select() to select contents of a div

Question by Conor Higgins

Is it possible to use or adapt jQuery’s .select() to set a selection range on the entire contents of a div?

I have a div which has a series of labels, inputs, select objects and a couple of other UI elements. I have found code on a separate StackOverflow post with some code hosted on jsFiddle: http://jsfiddle.net/KcX6A/570/

Can this be adapted to select the value of inputs also? Or how would you suggest I go about this?

Thanks,
Conor


Edit: More info

I know how to get the value of inputs using jQuery, that is easy, I also know how to select he values of independent elements using .select().

In my div I have a series of different element types including inputs, labels, selects, etc. I need an overall selection of all elements. The jsFiddle link I added earlier shows how to set the range of a div and select the text of elements like p tags etc. What I need is to set the range of the div’s contents and when I hit ctrl+c or cmd+c it copies the values of the inputs as well as the labels.

So to summarise, using .val and .select won’t work for this I don’t think. I need to combine the above in some way but not sure exactly how this will be accomplished. Any ideas?

Answer by techfoobar

Check this fiddle: http://jsfiddle.net/JAq2e/

Basically the trick is to introduce a hidden text node whose content will be included in the selection when copied.

Answer by Starx

If you want to select the input elements together with every thing.

Here is a jQuery mixed, JS solution

function selectElement(element) {
    if (window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        var range = document.createRange();
        range.selectNodeContents(element);
        sel.addRange(range);
    } else if (document.selection) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(element);
        textRange.select();
    }
}

selectElement($("div")[0]); //Select the div
$("input").trigger("select");  //select the inputs

Demo

March 22, 2012

How can i uncheck multiple select box options by class with jquery?

Question by tonymarschall

I have multiple multi-select boxes with the same class and i want to unselect all on an event. They have all a div with the same class class_for_all_multi_selects around them.

$("#element_to_uncheck_all_options").change(function() {
  $('.class_for_all_multi_selects'). ...?
});

<div class="class_for_all_multi_selects">
  <select multiple="multiple" name="1">
    <option value="1">option1</option>
    <option value="2">option2</option>
  </select>
</div>

<div class="class_for_all_multi_selects">
  <select multiple="multiple" name="2">
    <option value="1">option1</option>
    <option value="2">option2</option>
  </select>
</div>

How can i uncheck multiple select box options by class with jquery?

Answer by Jigs

you can also try this using prop:

 $("div.class_for_all_multi_selects option:selected").prop('selected',false);

check it out : http://jsfiddle.net/EVrrz/3/

Answer by Starx

Use removeAttr() to remove the selected attribute from all options

$('select option:selected').removeAttr("selected");

Since you said #element_to_uncheck_all_options is a div, you should bind to click events instead of change

$("#element_to_uncheck_all_options").click(function() {
   $('select option:selected').removeAttr("selected");
});
March 12, 2012

jquery selectors: how to select all li items from some index to the end?

Question by myWallJSON

So we can select one item li:eq('+(lastItemIndex)+')' I wonder how to select this item and all items that are next from it to the end? jsfiddle demo here (in which we would like to change all elements in li from 3 to last one)

Answer by Nicola Peluchetti

You should use nextAll();

var lastItemIndex = 3;
$('li').eq(lastItemIndex).nextAll('li').css("opacity", 0);​

http://jsfiddle.net/LN6ak/2/

Answer by Starx

You can combine :gt and :lt to create yourself a range selector

 $('ul li:gt(2):lt('+$('ul li').length+')')

Demo

March 7, 2012

jquery .serialize()

Question by Cjueden

I can’t get jquery .serialize() to work correctly. I have a form of dynamically generated checkboxes. The page wont submit the check boxes. Can you please tell me where I went wrong.

     $('#prof_take_attendance_submit').live("click",function(){
            var current_class = $('#class_choice :selected').attr('name');// GET CURRENT CLASS
            var prof_id = $('#prof_id').text();// GET PROFFESSOR ID NUMBER
                $("#prof_take_attendance_form").trigger('submit',function(){
                var query_string = $(this).serialize(); 
                        });

                $("#take_attendance_prof")// CALL TO FORM  
                .html(ajax_load)  
                .load(loadUrl, "form_being_submitted=prof_save_attendance&class="+current_class+"&prof_id="+prof_id+""+query_string);
        $('#take_attendance_prof').fadeIn(200);

     });

Answer by charlietfl

Based on assumption that $('#prof_take_attendance_submit') is a submit button you are trying to serialize just the button

Try:

   var query_string = $(this).closest('form').serialize(); 

Without more info about form is pretty hard to see what elese may not be working

EDIT: Get rid of trigger, bind submit to form not button

 $("#prof_take_attendance_form").live('submit', function(){
      var query_string = $(this).serialize(); 

       /* other code and ajax*/

 })

Answer by Starx

Serialize the form not the button

$("#prof_take_attendance_form").serialize();
May 11, 2011

jQuery select parent

Question by cabaret

This might be a duplicate question, however I did search and I got so many different answers that I don’t know which to use or how to do this.

<?
if(isset($content))
{
    $i = 1;
    foreach($content as $item)
    {
        echo "<li><a href='#' name='" . $item['id'] . "'>" . $item['title'] . "</a></li>";
        $i++;
    }
}
?>

I’ve added a function to these links with jQuery to handle an ajax call. I select the links as follows:

    $("#tips_list ul li a").click(function(e)   { //... }

However, this doesn’t make a lot of sense because now you have to click on the actual text instead of the list item. So I figured I’d re-structure my HTML so the anchor tag wraps around the li tag.

    `<a href="#" name=""><li>foo</li></a>`

I then changed my jQuery code accordingly:

    $("#tips_list ul a li").click(function(e)   { //... }

However, now, when I click.. it grabs the list item tag as $(this); which means I can’t really grab the name attribute from the anchor tag. So! What I need to do is to grab the name attribute from the parent anchor tag. And I honestly have no clue what the easiest way to do this is. I’m not that experienced with jQuery.

Thanks a lot for helping me!

Answer by phil

How about going back to the original method, and set #tips_list ul li a {display:block} in your CSS? That should make the a expand and take up the whole li, making the whole li seem clickable. Your original code should then work fine.

Answer by Starx

Keep the old markup. The later one is quite cranky and use the following script.

$("#tips_list ul li").click(function(e)   {
    var name = $(this).children("a").attr("name");
    alert(name);
}
...

Please fill the form - I will response as fast as I can!