jqueryonclickjquery-selectorsthisdisplay

Add Text to span complex field by Jquery


I want onclick event on <input> tag to display custom error in <span> placed tag just below it

I have many input readonly fields like,


<input class="form-control valid" id="OneOrder_line_items_0__Title" name="OneOrder.line_items[0].Title" onclick="clicked(this);" readonly="True" type="text" value="Burton T-Shirt" >

and span fields is (to display error like):


<span class="field-validation-valid" data-valmsg-for="OneOrder.line_items[0].Title" data-valmsg-replace="true"></span>

<name>, and, <data-valmsg-for>, are same in both tags

This is what i want to run

<script type="text/javascript">
    function clicked(item) {
        var id = $(item).attr("name");
        $('span[data-valmsg-for='+id+']').text('Your Text'); 
        //Here it is not working, if I hardcode it, $('span[data-valmsg-for="OneOrder.line_items[0].Title"]').text('Your Text'); then it works
    }
</script>

Can't understand what the problem is


Solution

  • Consider something like this:

    function clicked(item) {
      var id = $(item).attr("name");
      $('span[data-valmsg-for="' + id + '"]').text('Your Text');
    }
    

    Notice the Double Quotes.

    As you mentioned, this worked:

    $('span[data-valmsg-for="OneOrder.line_items[0].Title"]').text('Your Text');
    

    You can see how the ID, typed out, is wrapped by Quotes. The same has to be done for your script.