简体   繁体   中英

JS - Prevent append to be added multiple times

I have a form that has a mobile field. On submit button I put an event to add a value to the mobile field (it adds the country region code automatically which is a fixed value of "11"), so when the user clicks on Submit, the JS adds the "11" value to the mobile so the this field goes to the data base like this "1155555555" (the user just typed "55555555").

Ok, the problem is that if the user left an empty field (all fields are required), and clicks on Submit, the form won´t be sent but it will add the value "11" to the mobile field no matter what, and when the user fills up the empty field and click on Submit for the second time, it will add AGAIN the value "11", so the mobile goes like " 1111 55555555", and so on and so forth.

Basically, what I need is to prevent this function from happening multiple times. It has to happen only once. How do I achieve this using JS?

HTML:

   <input id="mobile" name="MOBILE" type="tel"><input type="number" value="11" id="front" class="hide">
 <button type="submit" onclick="append11()">SUBMIT</button>

JS:

    function append11(){
    var mobilenumber = document.getElementById("mobile");
  var front = document.getElementById("front").value;
  mobilenumber.value=front+mobilenumber.value;
  alert(mobilevalue.value);
}

I think you should heed the comment responses to your original question. Your approach has some risks.

But I'll assume you're a beginner who's just trying to learn how to do something like what you're asking about, so the javascript below applies a few principles you might consider.

 function isNumberValid9(num) { console.log(num, num.length); //check string length and pattern //this could be combined into a single regex, eg: mobileValue.match("^[0-9]{9}$") var isValid9 = num.length === 9 && num.match("^[0-9]+$"); console.log(isValid9); //display the value about to be returned return isValid9; } /* Conditionally prepend "11" */ function maybeAppend11() { var mobilenumber = document.getElementById("mobile"); var mobileValue = mobilenumber.value; //only prepend "11" if the number matches your expected pattern and length if (isNumberValid9(mobileValue)) { var front = document.getElementById("front").value; mobilenumber.value = front + mobileValue; } alert(mobilenumber.value); }
 <input id="mobile" name="MOBILE" type="tel" value="555555555"><input type="number" value="11" id="front" class="hide"> <button type="submit" onclick="maybeAppend11()">SUBMIT</button>

Why you don't append the 11 in the function?

Like:

function append11(){
  var mobilenumber = document.getElementById("mobile");
  mobilenumber.value="11"+mobilenumber.value;
  alert(mobilevalue.value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM