I am JavaScript beginner.  Now I want to set up a click popup based on my input.  My code is:

<div class="popup" onclick="myFunction()"> Equation
    <script scr="pop.js" type="text/javascript"></script>
</div>

code for pop.js:

function myFunction(){
    var o=getValuesFromForm();
    var ans=o.Group;
    var smn="";
    if (ans=='a'){
        smn += '<span class="poptext" id="myPopup" style="front-size: 80%">I am in group A</span>';
    }
    else {
       smn += ' <span class="poptext" id="myPopup" style="front-size: 80%">I am in Group B</span>';
    }
    $('#myPopup').html(smn);
    $('#myPopup').classList.toggle("show");
}

2 Answers

2
trincot On Best Solutions

Some issues:

  • jQuery does not expose a classList method. Just use the jQuery .show() method
  • There is some circular reasoning: You create HTML that includes a #myPopup element, but then you select an element with that id from the current page and try to set its HTML to that. You should decide which is going to be #myPopup... It's a chicken-egg problem. I would suggest that you include in your original HTML the #myPopup element, and don't use that ID for the dynamically added span element.
  • front-size should probably read font-size.

Here is how you can do it in a more jQuery style:

// Stub for the function you did not include:
function getValuesFromForm() {
    return Object.fromEntries((new FormData(document.forms[0])).entries());
}

function myFunction(){
    var o = getValuesFromForm();
    var ans = o.Group;
    var smn = $('<span>').addClass("poptext").css("font-size", "80%")
                         .text("I am in group " + ans.toUpperCase());
    $('#myPopup').empty().append(smn).show();
}
#myPopup {
    position: absolute;
    width: 300px;
    height: 50px;
    margin: 50px;
    border: 2px outset;
    display: none;
    text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
    <select name="Group">
        <option>a</option>
        <option>b</option>
    </select>
</form>

<button class="popup" onclick="myFunction()">Equation</button>

<div id="myPopup"></div>

0
SpeedOfRound On
function myFunction(){
var o={Group: 'a'};
var ans=o.Group;
var smn="";
if (ans=='a'){
  smn += '<span class="poptext" style="front-size: 80%">I am in group A</span>';
}
else {
 smn += ' <span class="poptext" style="front-size: 80%">I am in Group B</span>';
}

$('#myPopup').html(smn);
$('#myPopup').toggleClass("show");
}

As some people have mentioned, you needed to use .toggleClass because you are dealing with a jQuery object and not a DOM element.