选择选项值添加到查询字符串

时间:2019-02-10 12:54:52

标签: javascript php jquery

如何获取所选选项值的值并放入url查询字符串中

<td><select name="rate" id="rating" class="form-control col-sm-4">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
<td><a href="server.php?rate_id='.$table["rating_id"].'?r='[I want to put it here]' " class="btn btn-info" >Rate</td>

我尝试使用函数但将其放入,导致语法错误

$(document).ready(function() {
    $('#rating').on('change', get_value_rate);
});

function get_value_rate() {
    var selected = $('#rating').val();
    return selected;
}

我使用alert()函数,它获取值,但是在将do_something()放在查询字符串上后,它不能像所说的那样“返回”语法错误。

2 个答案:

答案 0 :(得分:2)

这就是我要使用纯JavaScript的方式。

您可以使用querySelector()函数查询DOM中的元素并获取选择值,使用模板字符串构建url,然后在锚标记上设置href属性。

您可以使用HTML附加事件侦听器:

<select ... onchange="onChange()">

或使用addEventListener()函数:

select.addEventListener('change', onChange);

这是querySelectoraddEventListener上的MDN文档。

如果您想从php绑定评级ID,建议在链接上绑定一个data属性,以后再使用该属性从JavaScript构造href。 我将此属性命名为data-rating-id,可以使用PHP进行如下设置:

<a href="#" data-rating-id="<?php echo $table["rating_id"] ?>">Rate</a>

const select = document.querySelector('#rating');
const link = document.querySelector('#link');
const ratingId = link.getAttribute('data-rating-id');

// Attach the event handler
select.addEventListener('change', onChange);

// Set the initial href for the link
setRateLink(select.value);

// Event handler
function onChange() {
  setRateLink(select.value);
}

// Function to generate URL and set href
function setRateLink(value) {
  const href = `server.php?rate_id=${ratingId}?r=${value}`;
  link.href = href;
  console.log(`href is "${href}"`);
}
<select name="rate" id="rating" class="form-control col-sm-4">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>
<a id='link' href="#" class="btn btn-info" data-rating-id="123">Rate</a>

答案 1 :(得分:0)

使用jquery并获取所选选项值的值并放入url

<td><select name="rate" id="rating" class="form-control col-sm-4">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
<td><a class="btn btn-info"  id ="link">Rate</a></td>

$(“#rating”)。change(function(){

val = $(this).val();

$(“#link”)。attr(“ href”,“ server.php?rate_id =” + val);

})

相关问题