Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to add and remove a span element dynamically. it's throwing syntax errors like

expected ')' and expected ';'

please help me to fix it.

<script type="text/javascript">
    $(document).ready(function () {
        $("input[data-required='true']").focus(function () {
            $(this).css({ 'background-color': 'red' }).after("<span class="label_error;"style="color:red;font-size:10pt">This field is required</span>");
        });

    $("input[data-required='true']").blur(function () {
        $(this).css({ 'background-color': 'white' }).remove("<span class="label_error;"style="color:red;font-size:10pt">This field is required</span>") ;
    });

    });
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
153 views
Welcome To Ask or Share your Answers For Others

1 Answer

The way that you are concatenating the values in your HTML string is wrong,

.after("<span class='label_error' style='color:red;font-size:10pt;'>" +
         "This field is required" +
        "</span>");

To fix this issue either you can use single quote in your string wrapped by double quotes or try to escape the double quote by using like "avi"s code is wrong".

On top of all, the best approach would be creating element by using jquery,

.after($("<span>", {class : 'label_error', 
                    style : 'color:red;font-size:10pt;',
                    text : 'This field is required'
                   }));

This would be more readable and maintainable. And I forgot to spot another one error that you made in your code. You are using .remove() in a wrong way,

$("input[data-required='true']").blur(function () {
   $(this).css({ 'background-color': 'white' }).next("span.label_error").remove();
});

You have to select the relevant element from your $(this) object and invoke remove over it.


And the best approach for finishing up your task is, allot the styling works to be done to the css by writing rules with relevant selectors (said by @rory)

input[data-required='true'] {
  background-color: white;
}
input[data-required='true']:focus {
  background-color: red;
}
span.label_error {
  color: red;
  font-size: 10pt;
}

And the js would be,

var errorMsg = $("<span>", {class: 'label_error',text: 'This field is required'});

$("input[data-required='true']").focus(function() {
  $(this).after(errorMsg);
}).blur(function() {
  $(this).next("span.label_error").remove();
});

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...