1

I'm pretty new to Ajax and JQuery. I'm trying to change the value of a span when I type text in an input box but nothing is working(i.e the value in the span is not changing). After some research around StackOverflow, I found out that I should either use the text() or html() of JQuery to change the value but it still does not change. I'm not sure where I went wrong. Below is my code:

Html of Input Box:

<input class="amnt" id ="Red:XL:50:24.55" type="text">
<span id="50-Red-24.55">0(This text is not changing)</span>

Here's my JQuery. It first performs an Ajax(I omitted this part) and then after Ajax success, it should change the value of my span:

$( ".amnt" ).keyup(function() {
    var split = this.id.split(":");
    var color = split[0];
    var size = split[1];
    var ID = split[2];
    var price = split[3];

    $.ajax({    //create an ajax request to getData.php
        success: function(response){                  

            $("#"+ID+"-"+color+"-"+price).text(price);
        },
        error:function (xhr, ajaxOptions, thrownError){
         alert(thrownError);
        }
    });
});

I also tried $("#"+ID+"-"+color+"-"+price).html(price); instead of $("#"+ID+"-"+color+"-"+price).text(price); but nothig changes on keyup. Can anyone please explain what I'm doing wrong here?

Thanks.

nTuply
  • 1,364
  • 19
  • 42
  • Are you sure that the AJAX call is successful and that all the variables are what you expect them to be? – Shomz Dec 25 '15 at 13:11
  • 3
    The issue is that periods in the selector is assumed to be classes – adeneo Dec 25 '15 at 13:12
  • @Shomz Yes the ajax call is successful, otherwise I would have gotten the alert(thrownError). I also tested the success with another alert and it worked. It's just the span that's not changing for some reason. – nTuply Dec 25 '15 at 13:13
  • 2
    @adeneo, you should write that as an answer, though note that the periods are legit parts of an ID, but jQuery is not the smartest to handle it. – Shomz Dec 25 '15 at 13:13
  • 2
    @Shomz - true, periods are valid, but must be escaped, and preferably one would just avoid special characters and make life easier. – adeneo Dec 25 '15 at 13:14
  • @adeneo I get what you mean. But the period is important is this case as it's part of the price. How would I go about to escape it and take it into consideration with the id? – nTuply Dec 25 '15 at 13:16
  • 1
    You could try `price.replace('.','\\.')` – adeneo Dec 25 '15 at 13:17
  • 1
    @adeneo, please write an answer so we can close this. – Shomz Dec 25 '15 at 13:20
  • @adeneo Excellent. This worked perfect. Please make it into an answer so others could benefit. And explain why this works and how the Javascript gets "confused" as well hehe :-) Thanks – nTuply Dec 25 '15 at 13:21
  • 1
    Nah, there's already good answers, and using an identifier that just indentifies the element, nothing more, and then using data attributes to filter on data etc, seems like a much better idea ? – adeneo Dec 25 '15 at 13:22
  • 1
    But you are the only one who pin-pointed the problem and did not take the other path. **I insist!** :) (if you give me your login credentials, I'll write it) – Shomz Dec 25 '15 at 13:24
  • @adeneo It is indeed a much better way of doing things to use data attributes. It's a bit hard for beginners to figure that out. But your answer is what matters for the question. Up to you if you want to put it or not :-) – nTuply Dec 25 '15 at 13:25
  • 2
    @user3029017 has already posted an answer showing how to *"escape"* string for jQuery selectors – adeneo Dec 25 '15 at 13:26
  • 1
    @nTuply, since it's the part of the price, you can replace that comma with pretty much any other legal ID character (except for a number, of course) and stay away from jQuery's problems. – Shomz Dec 25 '15 at 13:27
  • I see. Thanks @Shomz – nTuply Dec 25 '15 at 13:29
  • 1
    for your reference , [http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html](http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html) – Srinu Katari Dec 25 '15 at 14:07

3 Answers3

2

Instead of concatenating different items to create the Id string, It would be better and clean, if you use relative selectors in your code.

Add a css class to your message span and wrap this in a container div. Also instead of keeping your data inside the Id value, you may keep those in HTML 5 data attributes.

<div class="amtContainer">
  <input class="amnt" data-size="XL" data-price="24.55" type="text">
  <span class="amtMsg">0(This text is not changing)</span>
</div>

And in your script, use the closest() method to get a reference to the outer container div, and then use find() method to get to the message span.

$( ".amnt" ).keyup(function() {
    var _this= $(this);
    var val=_this.val();

    var price=_this.data("price");

    $.ajax({    //create an ajax request to getData.php
        success: function(response){                  

           _this.closest(".amtContainer").find(".amtMsg").text(price);
        },
        error:function (xhr, ajaxOptions, thrownError){
         alert(thrownError);
        }
    });
});
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Rewriting a piece of code is not equal to solving a problem with that code. @adeneo gave the correct answer. – Shomz Dec 25 '15 at 13:17
  • I like how you showed me the use of `data-price`, etc for a clean approach to my problem. I'll definitely use that as future reference but for now there's way to much code to edit. Why wouldn't my way work? – nTuply Dec 25 '15 at 13:17
  • 1
    I personally do not prefer to add more fixes to a complicated and unreadable solution than switching to a more clean and readable solution. Future code readability ( for you and your peers) is very important. JS is not a statically typed language and i am way too worried about keeping the code clean. There is no pressure. Use/write code the way you feel comfortable. This was my humble suggestion. Feel free to ignore it :) – Shyju Dec 25 '15 at 13:21
  • 1
    Yeah, but we're still on SO, not CodeReview. :) Just one character is the issue here - jQuery has issues with dots in the IDs, as @adeneo explained in the comments. – Shomz Dec 25 '15 at 13:23
  • I'm new and didn't know of that way you mentioned. It's clean and perfect for my future use(which I will actually adopt). Thanks for that. :-) However, my question is just different. – nTuply Dec 25 '15 at 13:23
2

First create the id concatenating the variables. Then replace . with \\. and use the modified id to select the span element. Then use .html() to change text in the span.

You can use this function to escape css selector characters from your id string

function jq( myid ) {

    return myid.replace( /(:|\.|\[|\]|,)/g, "\\$1" );

}

Reference: https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/

shakhawat
  • 2,639
  • 1
  • 20
  • 36
1

The problem (credits to @adeneo):

In the interpolated selector string, jQuery sees periods (which are perfectly fine ID characters) as class names, so something like "#my.cool.id" would actually select this element:

<div id="my" class="cool id"></div>

and not this one:

<div id="my.cool.id"></div>

The solution:

To avoid that issue, simply escape or replace the period in your price part of the ID with any legal ID character that's not a number or a period or a colon (since you're usign it for splitting), for example, 24X55, 24|55, etc. will all work fine.

Shomz
  • 37,421
  • 4
  • 57
  • 85