我有以下表单,单击“加入”按钮后,它应该更改为删除按钮。我想将文本更改为“删除”并更改其功能。
这是我的代码:
<form action="riderJoin.php" method="post">
<input type ="hidden" name = id value="<?php echo $row['post_id']; ?>" >
<input type =submit class="edit_btn " name = "submit" value = "Join">
</form>
<script type="text/javascript">
var x = document.getElementsByClassName('edit_btn');
<?php if (isset($_POST['submit'])) { ?>
var i = <?php echo $_SESSION['postId'] ; ?> - 1 ;
var y = x[i];
x[i].textContent = "Delete";
x[i].style.backgroundColor = "red";
x[i].style.color = "white";
<?php }?>
</script>
我已按类名将按钮放入 var x
中,并使用 x[i]
抓取 x 内的元素,但是当我尝试更改文本内容时它没有改变。但是,当我将背景颜色设置为红色时,效果非常好。
我做错了什么?
最佳答案
更新:更改按钮文本
创建按钮时,您可以看到要更改的文本位于 value
属性中:
<input type =submit class="edit_btn" name = "submit" value = "Join">
所以这就是您想要更改的内容 - 而不是 textContent
例如
x[i].value = "Delete";
更新:更改表单操作
要更改操作,首先您需要向表单添加一个 ID,以便我们可以在其中找到 javascript,例如
<form action="riderJoin.php" method="post" id="subscriptionform">
然后在 JavaScript 中,您可以获取它并更改操作,如下所示:
var formelement = document.getElementById('subscriptionform');
formelement.action = "newAction.php"; // set the action to whatever page you want
工作示例:单击按钮更改文本,新操作也会显示
function changebutton() {
// get the button and change it
var x = document.getElementsByClassName('edit_btn');
x[0].value = "Delete";
x[0].style.backgroundColor = "red";
x[0].style.color = "white";
// change the action of the form
var formelement = document.getElementById('subscriptionform');
formelement.action = "yourNewAction.php";
// Just for testing - gets the form action & displays it
updateStatusText();
}
// Just for testing - gets the form action & displays it
function updateStatusText(){
var formelement = document.getElementById('subscriptionform');
currentaction = formelement .action;
var textelement = document.getElementById('actiontext');
textelement.innerText= "The form action is: "+currentaction;
}
updateStatusText();
<form action="yourAction.php" method="post" id="subscriptionform">
<input type=submit class="edit_btn " name="submit" value="Click Me..." onclick="changebutton(); return false;">
</form>
<p id="actiontext"></p>
关于javascript - 如何在单击时更改表单的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46510031/