Harpo
Harpo

Reputation: 83

Change form button class depending on field input

I have a button in a form that has the class "popmake-46". The class makes it so that if the button is clicked a popup window opens. However, I want to make it so that the class changes to a different class (different popup) depending on the input of "zipcode".

If the zipcode starts with the numbers "117", the class should remain as "popmake-46", but if it starts with any other number, it should change the class to "popmake-47" (different popup window).

<form name="form1">
 <input type="text" name="firstname" placeholder="First name"><br>
 <input type="text" name="zipcode" placeholder="Zipcode"><br>
 <input class="popmake-46" type="submit" value="Submit">
</form>

How can I achieve this?

Upvotes: 0

Views: 178

Answers (1)

Xhynk
Xhynk

Reputation: 13880

I don't believe this is WordPress specific, it seems you just need to add an onchange and/or onkeyup event handler to your zipcode field.

I'm not sure of how you're implementing this form exactly, so here's a pretty basic way to do it:

  • Create a function that checks the value of the current element
  • If the value starts with '117' add the -47 class and remove the -46 class
  • Otherwise remove the -47 class and add the -46 class back.
  • add that function to the onchange and/or onkeyup event for the zip code.

In the snippet below I've added a little CSS (and changed your submit input to a button so I could use the ::after CSS pseudo-class to illustrate that it's changing based on what class it currently is.

function toggle46or47(el){
  var form = el.closest('form');
  var popMake = form.querySelector('[type="submit"]');
  
  if( el.value.substring(0, 3) == '117' ){
    popMake.classList.remove('popmake-46');
    popMake.classList.add('popmake-47');
  } else {
    popMake.classList.add('popmake-46');
    popMake.classList.remove('popmake-47');
  }
}
.popmake-46:after{content: " I'm 46";}.popmake-47:after{content: " I'm 47";}
<form name="form1">
 <input type="text" name="firstname" placeholder="First name"><br>
 <input type="text" onchange="toggle46or47(this);" onkeyup="toggle46or47(this);" name="zipcode" placeholder="Zipcode"><br>
 <button class="popmake-46" type="submit" value="Submit">Submit</button>
</form>

Upvotes: 1

Related Questions