Jackson
Jackson

Reputation: 264

How to append a text only one time using jquery and how to remove validation message once option is changed

I want to append an error message under a select box when next button is clicked if no options are selected. My code is

jQuery(document).ready(function() {
    setTimeout(function(){
        jQuery(".ladda-label").attr('onclick','onit()');
    },500);

});

function onit(){
    jQuery(".spn").append(" <b>Appended text</b>.");
}

I want the text only to append just once. i have tried several methods mentioned here but nothing seems to working for me.

I have one more concern , how can i remove the validation message once an option is selected.

Upvotes: 0

Views: 1115

Answers (5)

Elmer Dantas
Elmer Dantas

Reputation: 4869

You need to clean you span first:

jQuery(".spn") .find("#error-message") .empty() .append("<span id='error-message' style='font-weight:bold;'>Appended text</span>.");

when the user changes selection:

$("your select element").on("change",function(){
    $("#error-message").empty()
});

Regards

Upvotes: 0

Alexis
Alexis

Reputation: 5831

You can bind your event on the button click instead of add custom attr with your function...

$(".next-btn").click(function(){
  if($(".ddlist").val() == "-1"){
    $(".appender").html("<b>Please choose an option</b>");
    return false;
  }
  console.log("Select option choosed");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="ddlist">
<option value="-1">Choose</option>
<option value="1">1</option>
</select>

<button class="next-btn">Next</button>

<div class="appender"></div>

Upvotes: 0

mmm
mmm

Reputation: 1155

to modify the element only once, you can save the state of modification with data like that

function onit() {

    var element = jQuery(".spn");

    if ("yes" !== element.data("modified")) {
        element.append(" <b>Appended text</b>.");
        element.data("modified", "yes");
    }

}

Upvotes: 0

Elvin Haci
Elvin Haci

Reputation: 3572

function onit(){
if (jQuery(".spn").html().length==0)
    jQuery(".spn").append(" <b>Appended text</b>.");
}

Upvotes: 0

St&#233;phane Ammar
St&#233;phane Ammar

Reputation: 1454

You can use jquery one function

jQuery(document).ready(function() {
    setTimeout(function(){
        jQuery(".ladda-label").one('click',onit);
    },500);

});

function onit(){
    jQuery(".spn").append(" <b>Appended text</b>.");
}

Upvotes: 1

Related Questions