I'm trying to set a value for a dropdown list by clicking on a link(links to the same page), and the value that i want to set for the select is in the link.
I tried to do it this way, but because it is messed up it didn't work.
Here's the code i used:
<html>
<body>
<select id="select">
<option value="one">Pen</option>
<option value="two">Paper</option>
<option value="three">Book</option>
</select>
<a class="link1" href="page.php?cc=three">Set select value</a>
<script>
function $_GET(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
var cc = $_GET('cc');
var elmnt = document.getElementsByClassName('link1'),
selectClasse = document.getElementById('select');
function setSelect () {
for (var i = 0; i < elmnt.length; i++) {
elmnt[i].onclick = function () {
selectClasse.value = cc;
}
window.history.pushState('Form', 'My form', this.getAttribute("href"));
return false;
};
}
}
setSelect ();
</script>
</body>
</html>
Any help would be much appreciated.
If you want to do this with a link and its url parameters;
Based on the answer: https://stackoverflow.com/a/979996/2956448
So you can do it like;
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
var cc = params.cc;
var element = document.getElementById('select');
element.value = cc;
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.