简体   繁体   中英

Form Submit on Toggle click

I am working on a plugin for my WordPress site but I am stuck on this one part. I have managed to create a form that when clicked, changes the prices on the website (showing with and without VAT)*. The problem I am having is that I want it to be a toggle not two buttons but I cannot seem to find the right code anywhere. I have found code that creates a toggle but it doesn't submit the form when pressed.

I want it to submit the form when clicked and stay clicked until the user clicks it again.I am sure you can do this with JavaScript but I am not sure on how.

I am probably missing something obvious but I just cannot seem to work this one out.

Any help would be greatly appreciated

  • Please note I understand that this would be not recommended for an e-commerce site but the site is a lead generator.

example of the HTML with two buttons not a toggle

<form action="" method="post">
<input type="submit" name="personal" value="personal">
<input type="submit" name="business" value="business">
</form><br>

example of PHP

function adds_personal_toggle() {
if (isset($_POST["personal"])) {

$_SESSION['personal'] = 'personal';

}

if (isset($_POST["business"])) {

unset($_SESSION["personal"]);

}

}

I think a single button is sufficient to achieve whatever you are looking for. Set the required value in request attribute.

$_REQUEST["key"] = "Personal" or "Business";
if ($_REQUEST["key"] is "Personal") {        
    // button generation code for Personal;
}

if ($_REQUEST["key"] is "Business") {   
    // button generation code for Business;        
}

Also you can manipulate your action inside form tag with the help of above if statements.

action="php_file.php?type=Personal or Business"

Proper usage of if statements will generate only one button with "Personal" or "Business" as per your requirement.

Found the answer and thought I would share if anyone had similar problems.

if you use

<input type="checkbox" value="personal" name="personal" onchange="document.getElementById('INSERT FORM ID HERE').submit()" <?php echo $checked; ?> ></input>

it will submit the form when the checkbox is clicked. Also if you add

$checked = 'checked';

Into the if statement in the PHP file, the toggle will stay checked once the it has been selected.

Hope that helps someone.

in your function toggle button call your update fuction

Example given below:

    function Toggle() {
     //your code here for toggle
     Update()
    }

    function Update() {
    // your code for update
    }

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