简体   繁体   中英

How to create a function using javascript which will check a field value/user input and show alert if the input is correct?

I am trying to create a function using javascript which will check what the user inputted in a field when the form is submitted and if the value inputted is correct (based on predefined value) to show an alert. So far I have this:

function checkFieldAndShowPopup(fieldValue, predefinedValue) {
 predefinedValue = 5;
 fieldValue = document.getElementById('kdxalh').value;
 if (fieldValue === predefinedValue) {
 alert('Field input is correct!');
 }
}

My problem is that I cannot change the submit button to run to have an onclick event so I can run the function. Is there a way to run the function without onclick event?

I have tried to change the submit button to have an onclick event but since I am using a framework with form builder I am not able to pass it.

Form:

<form id="contact-form106">
   <div class="breakdance-form-field breakdance-form-field--text">
   <label class="breakdance-form-field__label" for="kdxalh"> Your Answer 
    <span class="breakdance-form-field__required">*</span>
   </label>
   <input class="breakdance-form-field__input" id="kdxalh" aria-describedby="kdxalh" type="text" name="fields[kdxalh]" placeholder="" value="" required="">
   </div>
   <footer class="breakdance-form-field breakdance-form-footer">
   <button type="submit" class="button-atom button-atom--primary breakdance-form-button">
  <span class="button-atom__text">Submit</span>
  </button>
  </footer>
</form>

you can do that by addEventListener() method, for example

<button type="submit" id="elmId" class="button-atom button-atom--primary breakdance-form-button">
  <span class="button-atom__text">Submit</span>
  </button>

var elm = document.getElementById("elmId")
elm.addEventListener("click", myFunction);

function myFunction() {
  // do what ever you need
}

Very interesting framework that doesn't give you the control of events!

But anyway i'll try to suggest you other ways of implement what you want, though they could be not perfect from the perspective of definition "good code".

1

you can try to find that form or maybe that button (if it's not has the random hash) and add listener to it directly

const form = document.querySelector("form-wrapper > div  form")
form.addEventListener("submit",()=>{alert("Hi mom")})
const button = document.querySelector("form-wrapper > div form > button")
button.addEventListener("click",()=>{alert("Hi mom")})

2

you can listen another event, but maybe that's not what you wanted You can listen change event of input, and when it's correct just show your pop-up

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