0

Below is a fiddle I am experimenting with. Basically I am looking to update the dynamically appended spans to the preview div when there is a change in value on the input fields. The value of the input is available in the alert, but it does not seem to be updating the span. I also find it strange that if you simply select the span with the dynamically generated ID and alert the text, that it has no value. Any thoughts? I am avoiding using knockout for what it is worth.

http://jsfiddle.net/Wr3t7/4/

$(document).ready(function(){
     $(".project").each(function(index, value){
         var titleElem = $(this).find(':nth-child(1)');
         var projId = "#" + titleElem.attr('id') + "_Prev";

         $("#previews").append("<span id='" + projId + "'>" + titleElem.val() + "</span><br/>");

         titleElem.keyup(function(){
             alert($(this).val());
             $(projId).text($(this).val()); 
         });
     });
 });

The goal is a I want this logic to be able to handle any number of project divs that might show up on the view.

2
  • 1
    You're setting the id of your span incorrectly. You're including the # character in the id, which you should not (though you do, of course, need it in the jQuery selector when getting the element from the DOM. Just out of curiousity, why are you trying to avoid Knockout (and all the other databinding libraries out there)? Commented May 20, 2014 at 15:28
  • We just didn't use it for other views in the project I am working on and didn't feel one view warranted its inclusion. Thanks for the catch I completely missed that! However, it still is not working (have updated my fiddle). Commented May 20, 2014 at 15:33

3 Answers 3

2

Few work arrounds

1) [] are not allowed in IDs you're having as they are reserved for attribute selectors.
2) setting # at the time of initializing a string variable is not valid.
3) Set text to <span> Directly will not work you need to write # for selecting <span> object.

So combinng all your code should look like this:

As you said that markup is generated by MVC code, you can create new IDs of span using regex Expression

var newProjIdID =  projId.replace(/[^\w\s]/gi, ''); // Generating valid ID

So ultimately final answer will be this:

jQuery

$(".project").each(function(index, value){
        var titleElem = $(this).find(':nth-child(1)');
        var projId = titleElem.attr('id') + "_Prev";
        var newProjIdID =  projId.replace(/[^\w\s]/gi, ''); // Generating valid ID
        $("#previews").append("<span id='" + ID + "'>" + titleElem.val() + "</span><br/>");

        titleElem.keyup(function(){
            alert($(this).val());
            $("#" + ID).text($(this).val()); 
        });
    });

Fiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

I think maybe you missed my comment, asp.net mvc is rendering arrays with an ID value that contains the brackets.
1

You have two problems:

  1. You are setting the id of the appended spans to #foo (i.e. including the hash as part of the id)
  2. The square brackets in the id, although valid in HTML 5, are confusing jQuery i think

if you can't change the id's on the inputs, at least change them on the spans

$(document).ready(function(){
    $(".project").each(function(index, value){
            var titleElem = $(this).find(':nth-child(1)');
            var projId = titleElem.attr('id').replace('[', '_').replace(']', '_') + "_Prev";

            $("#previews").append("<span id='" + projId + "'>" + titleElem.val() + "</span><br/>");

            titleElem.keyup(function(){
                alert($(this).val());
                $('#' + projId).text($(this).val()); 
            });
    });
});

Working fiddle

4 Comments

I will mark this as the answer as it does resolve the problems I am having and I have no real opposition to changing the spans to non []'d Ids. However, I think the ultimate issue is why I am getting brackets rendered by ASP.Net MVC in the first place, but that is another issue I will have to look into. Many thanks Adam!
@Shawn: I edited my original post to work with the brackets without doing a replace. Check it out.
I see that, I am not sure why when I escaped them it didn't behave. Kudos to solving that!
@Shawn: when you escape it make sure you use 2 forward slashes, not just 1. In my jsfiddle you will see it does id.replace("[", "\\").
1

jquery selectors are pretty much regular expressions so you need to escape your brackets:

http://jsfiddle.net/Wr3t7/14/

<body>
    <div id="projects">
        <div class="project">
            <input type="text" id="ProjectViewModel_[0]_Title" value="Title1"/>
        </div>

        <div class="project">
            <input type="text" id="ProjectViewModel_[1]_Title" value="Title2"/>
        </div>
    </div>

    <div id="previews">

    </div>
</body>

$(document).ready(function(){
    $(".project").each(function(index, value){
        var titleElem = $(this).find(':nth-child(1)');
        var projId = titleElem.attr('id') + "_Prev";

        $("#previews").append("<span id='" + projId + "'>" + titleElem.val() + "</span><br/>");

        titleElem.keyup(function(){
            $("#" + projId.replace('[', '\\[').replace(']','\\]')).text($(this).val()); 
        });
    });
});

9 Comments

The problem is ASP.Net MVC renders the array with Id names containing the brackets, so this doesn't really resolve the problem.
if you look at w3.org/TR/html4/types.html#type-id you will see that "ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").". So your real issue is to figure out how to get rid of those brackets through MVC
@jnoreiga: That reference is for HTML4. Pretty much anything except spaces are allowed in IDs in HTML5 (the fiddle at least is HTML5). Whether it is a good idea to use them or not is debatable, but it's valid i think. I think the problem is that jQuery uses square brackets as attribute selectors in its selector syntax. See w3.org/TR/html51/dom.html#the-id-attribute for HTML 5 reference ("There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc")
@Adam: I updated it for you. This method works with your brackets
@Shawn: No worries. Just making you aware that you can escape reserved characters in your selectors just in case you run into it again with another element attribute.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.