如何解决想要使用JQUERY导致发布单个选定表单值
我正在生成一个键/值数组,并在其中滚动以在表单内生成一组“ a”标签。 我希望JQuery检测到已单击了'a'标记之一,然后提交表单,以便发布KEY而不是值。 我构建的test.php文件似乎无法使用JQuery函数。
<?php if(isset($_GET['id'])) {
echo '<h2>URL parameter passed by $_GET</h2>' ;
echo '<pre>' ;
echo print_r($_GET) ;
echo '</pre>' ;
} elseif(isset($_POST['id'])) {
echo '<h2>URL parameter passed by $_POST</h2>' ;
echo '<pre>' ;
echo print_r($_POST) ;
echo '</pre>' ;
}
?>
<style>
table {
width:50%;
}
td {
width:25%;
border:1pt solid black;
margin:0px;
}
</style>
<?php
// Build Indexed Array
$fruit[0] = 'Orange' ;
$fruit[1] = 'Apple' ;
$fruit[2] = 'Banana' ;
echo '<pre>' ;
echo print_r($fruit) ;
echo '</pre>' ;
// Form definition
echo '<form name="groupform" id="groupform" action="test.php" method="post">' ;
echo '<table>' ;
echo '<tr><td>Array values</td><td>Simple A tag</td><td>Regular submit button</td><td>A tag with class submit</td></tr>' ;
for($key = 0; $key < count($fruit); $key++) {
echo '<tr>' ;
// Array Values
echo '<td>Index is ' . $key . ',value is ' . $fruit[$key] . '</td>' ;
// Simple A tag
echo '<td><a href="?id=' . $key . '">' . $fruit[$key] . '</a></td>' ;
// Regular submit button
echo '<td><input type="submit" name="id" id="id" value="' . $fruit[$key] . '"></td>' ;
// A tag with class submit
echo '<td><a href="" class="submit" name="id" id="id" value="' . $key . '">' . $fruit[$key] . '</a></td>' ;
echo '</tr>' ;
}
echo '<tr><td></td><td>Functions correctly,but don't want to use a URL parameter to send the key</td><td>Can't get this to post the key instead of the value</td><td>Ideally want to style it as an a tag,but post the key</td></tr>' ;
echo '</table>' ;
echo '</form>' ;
?>
<script src="/scripts/jquery-3.3.1.js"></script>
<script>
$(function(){
// when clicking the submit button
$('.submit').click(function(){
// Get the value of the clicked a tag
var usethisID = $(this).val();
alert(usethisID);
// submit the form
// BUT POST the value of usethisID as id
$('#groupform').submit();
});
});
</script>
解决方法
var usethisID = $(this).attr(“ value”);
要小心,在DOM中,不能有带有相同“ id”的标签! 每个id =“必须具有唯一值! https://developer.mozilla.org/en-US/docs/Web/API/Element/id
因此,我建议使用$ key构造每个'id':id_XXXX
echo '<td><a href="" class="submit" name="id" id="id_'.$key.'" value="' . $key . '">' . $fruit[$key] . '</a></td>' ;
在jQuery中,您从id中提取$ key:
<script>
$(function(){
// when clicking the submit button
$('.submit').click(function(){
// Get the value of the clicked a tag
var index = $(this).attr("id");
var usethisID = index.substring(index.indexOf("_")+1 );
alert(usethisID);
// submit the form
// BUT POST the value of usethisID as id
$('#groupform').submit();
});
});
</script>
好的延续。
_Teddy _
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。