0

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

2
  • The " around id is missing, try: $(`span[data-valmsg-for="${id}"]`).text('Your Text'); Commented Jul 23, 2024 at 19:59
  • Welcome to Stack Overflow. As was mentione,d you need to wrap your value in Double Quotes so that jQuery knows what you are looking for. Presently, it is unwrapped and will not be read right. Commented Jul 23, 2024 at 23:14

1 Answer 1

1

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.

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

Comments

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.