简体   繁体   中英

Using variable from forms as DOM selectors

I thought I was past the point where I get tripped up on small stupid things but I can use some help. I'm trying to use a variable that is made from form input so select (either using JS or jQuery) an element by ID. The end goal is to remove certain elements in the HTML base on the selection.

Javascript/jQuery that I have and some things I've tried.

function showLocation() {
    var locationRef = document.getElementById("ddlViewBy"),
        locationChoice = locationRef.options[locationRef.selectedIndex].value,
        selectionChoice = document.getElementById("selectionChoice");

    (function() {
        $('#locationChoice').toggleClass("ClassHide");
        return false;
    })();
});

Instead of the $('#locationChoice') I've tried just $('locationChoice') and $(locationChoice).

When I console.log(locationChoice) I get the correct selection so I don't think its that.

I also tried without jQuery

locationChoice.classList.remove("classHide");

Here is the HTML

<form onsubmit="return showLocation()" id="testLocation">
<h4>Please select a location</h4>
<select id="ddlViewBy">
    <option value="spotOne">Test Spot One</option>
    <option value="spotTwo">Test Spot Two</option>
</select>
<button type="submit" form="testLocation" value="Submit">Select</button>

<div id="spotOne">
    <p>Remove Me One</p>
</div>
<div id="spotTwo">
    <p>Remove Me Two</p>
</div>

Any typo's or syntax errors may be from cleaning everything up and pasting it. I really appreciate the help.

You just need to concatenate the '#' to your locationChoice variable.

$('#' + locationChoice)

Or change your values to be actual selectors:

<option value="#spotOne">...</option>
$(locationChoice);

If you change the way the toggleClass works to the following, it should fix the error:

$("#" + locationChoice).toggleClass("ClassHide");

This adds the "#" to whatever the locationChoice is that the user chooses.

To build on top of @Quantastical answer.

There are actually 2 errors:

  1. Given that locationChoice is a string we will need to do: $('#' + locationChoice);

  2. The immediate function within your function has a return, but your original function doesn't.

I don't quite understand the intent with the immediate function; however, simply add a return to make it work.

return (function() {
$("#" + locationChoice).toggleClass("ClassHide");
return false;
})();

or without the function:

$("#" + locationChoice).toggleClass("ClassHide");
return false;

See: Working example

Edit: Also make sure to check out @Barmar recommendation given as a comment to your post.

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