Home > Software design >  How to create a function using javascript which will check a field value/user input and show alert i
How to create a function using javascript which will check a field value/user input and show alert i

Time:12-14

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 >
   <label  for="kdxalh"> Your Answer 
    <span >*</span>
   </label>
   <input  id="kdxalh" aria-describedby="kdxalh" type="text" name="fields[kdxalh]" placeholder="" value="" required="">
   </div>
   <footer >
   <button type="submit" >
  <span >Submit</span>
  </button>
  </footer>
</form>

CodePudding user response:

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

<button type="submit" id="elmId" >
  <span >Submit</span>
  </button>

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

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

CodePudding user response:

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

  • Related