简体   繁体   中英

Using javascript to change <a> tag to use selected option value

I'm building a select list within a modal using a PHP loop.

The options display properly,and upon inspecting elements they are showing the appropriate option value (pageID) as well:

<select name="pageToAssign">
     <?php foreach($activePages as $pages):?>
     <option value="<?php echo $pages['id']?>"><?php echo $pages['id']?><?php echo $pages['title']?></option>
     <?php endforeach?>
</select>
<a href="assignPage.php?pageID=<?php echo $pages['id']?>&displayID=<?php echo $_GET['displayID']?>" class="btn btn-primary" role="button"> Assign Page</a>

The issue is that when I click my submit link, it hits my php script and performs the update in my database but it's with the wrong page ID. It always uses the last pageID of the array that builds my options in the select.

How can I possibly use javascript in order to make sure the pageID in my tag changes with each option select?

Alright, so first I added the id to the link so we can target it easily.
Next I added an id to the select for the same reason.
Then I created a change event handler for the select and added logic to it to first get the existing href, replace the pageID with the new value, and then set it back as the href on the link, so it keeps the displayID parameter.

I removed the php parts so it could be tested in the runnable snippet.

 document.getElementById('pageToAssign').addEventListener('change', function() { var assignPage = document.getElementById('assignPage'); var href = assignPage.getAttribute('href'); assignPage.href = href.replace( /pageID=[^&]+/, 'pageID='+ this.value ); }); 
 <select name="pageToAssign" id="pageToAssign"> <option value="10">10</option> <option value="15">15</option> <option value="43">43</option> </select> <a href="assignPage.php?pageID=0&displayID=67" class="btn btn-primary" id="assignPage" role="button"> Assign Page</a> 

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