How to produce an effect when a checkbox button is checked while using jQuery? [duplicate]

I’m trying jQuery from scratch & I want to produce an effect when a checkbox button was checked, with jQuery. But I’m not having the effect I want.

<div>
    <input type="checkbox" id="cb">
    <label for="cb">Show Button</label>
</div>
<button id="but">
    Button
</button>

$(() => {
    $("#but").hide();
    $("#cb").on("change", () => {
        if($(this).is(":checked")) {
            $("#but").show();
        }
    });
});

I realized it is not entering to the if block. I guess checked prop should be called on a different way? How can I make this work?

XSS PoC: Hide Rendered Characters in DOM

I’ve started playing with XSS to better improve my security posture at work. I’ve been able to successfully exploit a reflected XSS attack using a redirected POST form, but I can’t seem to remove the extraneous characters displayed on the page.

I’ve checked:

XSS: Character showing in DOM

https://security.stackexchange.com/questions/207282/xss-character-showing-in-dom?newreg=61e9890d94d34d0c8818158ba541b117

How to load javascript on another webpage through XSS?

But none of the suggestions seem to work for me.

My exploit is a basic form, exploiting a PHP server side script I’ve configured echoing $_POST['username'] into the value attribute:

<form id=1 method="post" action="http://vulnerable.site.com">
    <input type="hidden" name="username"
    value="&quot;&gt;&lt;script&gt;alert('Hello');&lt;/script&gt;&quot;">
</form>
<script>
    document.getElementById(1).submit();
</script>

Unencoded:

<form id=1 method="post" action="http://vulnerable.site.com">
    <input type="hidden" name="username"
    value=""><script>alert('Hello');</script>">
</form>
<script>
    document.getElementById(1).submit();
</script>

But this pesky "> will not die:

Extra characters rendered

I’ve tried:

  • Several filter evasion techniques by adding additional characters recommended by OWASP
  • Escaping the "> to &quot;&gt; – this results in syntax errors, and removing the leading quotes breaks the payload. BUT, based on resources linked above, it seems possible based on comments
  • Using CSS selectors to hide the characters in my attack payload (using dev tools, the "> shows up as #text so I thought this might work)

I’m sure it’s something silly, but what am I missing? It’s clearly possible, but I’m not a skilled web developer (hence the fiddling around). Any feedback or advice would be appreciated!

How to create test using Jasmine framework?

Can someone help me please. How can I create a single test using Jasmine framework to test global array called “numArray”(e.g. let numArray=[6,1,8,3,12]) with the following:

  1. It must have at most 7 elements
  2. It must have the number 1 and 2 as any of it’s elements
  3. The total of all numbers in the array must be 30

Note: I can’t access individual elements to perform test, (e.g. numArray[3]), sample data may be any length.

Thank you in advance.

How to change the display month and year in javascript calander on user search

i have a php website where i used a javascript calander to display events on particular date, everything is working fine, now i have given a search box for user to serch and display the month and year he wants:

<select class="form-select" id="basicSelect" name="month">
                                                      <option value="01">January</option>
                                                      <option value="02">February</option>
                                                      <option value="03">March</option>
                                                      <option value="04">April</option>
                                                      <option value="05">May</option>
                                                      <option value="06">June</option>
                                                      <option value="07">July</option>
                                                      <option value="08">August</option>
                                                      <option value="09">September</option>
                                                      <option value="10">October</option>
                                                      <option value="11">November</option>
                                                      <option value="12">December</option>


                                                  </select>

  <select class="form-select" id="basicSelect" name="year">
                                                      <option value="2022">2022</option>
                                                      <option value="2021">2021</option>
                                                      <option value="2020">2020</option>
                                                      <option value="2019">2019</option>
                                                      <option value="2018">2018</option>
                                                      <option value="2017">2017</option>
                                                      <option value="2016">2016</option>
                                                      <option value="2015">2015</option>
                                                      <option value="2014">2014</option>
                                                      <option value="2013">2013</option>
                                                      <option value="2012">2012</option>


                                                  </select>

the calander iused was from here https://codepen.io/romswellparian/pen/raPObG , as i am new with javascript and jquery can anyone please tell me how to accomplish this, thanks in advance

How to use jQuery libraries on a project with npm?

I’m trying jQuery for the first time, I know this library is becoming more and more unused, but I need it to work with it on a project.

So I initialized a jQuery project with npm install jquery, so node modules and package-lock.json were created. I wonder how should I target library files on the index.html file, I mean maybe it should be something like this <script src="./node_modules/jquery/"></script>. Also how should I use libraries on .js files.

I don’t know if I should point file by file or how should I use library files. Maybe someone could guide me with examples or docs on how to start using a jQuery libraries on a project.

How to draw lines with captions on an image with javascript?

I have a website contains pipeline image and I’m trying to figure out how to draw multiple lines with captions addressing specific position of the image. Any good ways or library I can try that helps to do this well?

This example is what I expect.
enter image description here

I currently only have pipeline image with transprent background and pixels of positions I want to connect the lines.

javascript one eventlistener to rule them all vs multiple listeners (best practice)

Hi I have been looking on the internet trying to figure out the best practice for adding eventlistener to my websites and it generally comes down with two approaches as follow:

Adding an event listener to every elements (e.g. button) using a loop:

document.querySelectorAll('.some-button').forEach(item => {
    item.addEventListener('click', event => {
        //handle click
    })
})

Or using event bubbling to use one listener only and check the e.target for each scenario:

body.addEventListener('click', event => {
    if (event.target !== element1 && event.target !== element2) {
        //return
    }
    //handle click
}

However, I was unable to find any article comparing the performance of these 2 approaches. From my limited understanding, whenever there is a ‘click’ javascript will loop through all the eventlisteners anyway (even though if you didn’t click on it) and for that reason I am taking the second approach (using one eventlistener) which seems to be the easier one to manage.

Appreciate if someone can provide further insights on the potential drawback of the second approach and if there will be any performance issue thanks.

Can an tag send a GET request?

I’m building a website in Node.js, Express, and EJS. In the past, I have created forms where the button is of type="submit". I would then have my index.js file do a res.render to pull up the ejs file I’m trying to route to.

Right now, I’m trying to route from an <a> tag to an ejs file called "/jsonData".

I’ve added the GET request in my index.js file:

app.get('/jsonData', (req, res) => {
    res.render('jsonData');
});

and I’ve added the a tag in my home.ejs file:

<li class="nav-item">
   <a class="nav-link" href="/jsonData">JSON Data</a>
</li>

My jsonData file is in my views folder because I set app.set('view engine', 'ejs'); earlier in the index.js file.

My home.ejs file runs great when I start the server using node index.js, but when I click on the link to go to my jsonData page, I get the error:
Cannot GET /jsonData

I’m sure I’m probably doing something obviously wrong but I don’t know what to do.

Thank you in advance!!

Pass paragraph to another page JavaScript/HTML

I know there are similar questions about it but I’ve stumbled on different problem. I have a lots of paragraphs in my page and I want to add “favorite” buttons to every single one of them. So far I’ve attached “favorite” button to one of them and passed it to another page. One more thing… I want to add those favorited paragraphs like a list. Simply I want to make FAVORITES page. This is my first page:

<form action="pages/login_screen.html">
    <p id="first">A<span id="heart"><i class="fa fa-heart-o" aria-hidden="true"></i></span></p>
    <script>
            $(window).on('load',function(){
              if(localStorage.toggled != "with_toggle"){
                $("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
              }else{
                $("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
              }
            });
            $('#heart').toggleClass(localStorage.toggled);
            $('#heart').on('click',function(){
              if (localStorage.toggled != "with_toggle") {
                $("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
                $('#heart').toggleClass("with_toggle", true);
                localStorage.toggled = "with_toggle";
                localStorage.removeItem("paragraphValue");
              } else {
                $("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
                $('#heart').toggleClass("with_toggle", false);
                localStorage.toggled = "";
                var paragraph = document.getElementById("first").innerHTML;
                localStorage.setItem("paragraphValue", paragraph);
                return false;
              }
            });
    </script>
    <button><a href="pages/login_screen.html">GO</a></button>
    <p>B</p>
    <p>C</p>
    <p>D</p>
    <p>E</p>
    <p>F</p>
    <p>G</p>
</form>

And this is my second Page:

<span id="favorites"><!--FAVORITES HERE--></span>
<script>
    document.getElementById("favorites").innerHTML = localStorage.getItem("paragraphValue");
</script>

How To Store A Element Inside A Map Using Dynamic Variable In Firebase

I Wanted To Know How We Can Store Elements(Map) Inside A Map With Dynamic Element Names.
I Tried The Following

var activequestionid = "12201"
var aqid = "answers."+activequestionid
await updateDoc((doc(db, "tests", testid), {
      [`${aqid}`]: {ans:ans,type:type,time:serverTimestamp()}
    }))
var activequestionid = "12201"
var aqid = "answers."+activequestionid
await updateDoc((doc(db, "tests", testid), {
      [aqid]: {ans:ans,type:type,time:serverTimestamp()}
    }))

Also My Map Is As Follows:

testid(document)
    answers(map)
        12201(map)

But Both Give The Same Error: Expected type 'Pc', but it was: a custom Object object
Any Help On This Issue Is Appreciated!

Calling a function from a JS file not working

I’m using React to view my pages.
I came across this problem if I try to call a function from a .js file nothing happens.
Basically, I have a small program that has two columns. Each column has a <p> tag that contains Column 1 and Column 2. There is a button below that once you click on it, both Columns should switch.

index.js

import "../style.css";
//import "./java.js";

const index = view => {
    return(
        <div className="container">
            <div className="columns" id="columnsToSwitch">
                <div className="column1" id="column1_id">
                    <p>Column1</p>
                </div>
                <div className="column2" id="column2_id">
                    <p>Column 2</p>
                </div>
            </div>
            <div className="switch" id="switch_id">Switch</div>
        </div>
    );
}

export default index;

java.js

const switchCol = document.querySelectorAll(".switchCol");

const el = document.getElementById("switch_id");
if(el) {
    el.addEventListener("click", switchColumns, false);
}

switchCol.forEach(switches => {
    switches.addEventListener("column1", switchColumns);
    switches.addEventListener("column2", switchColumns);
});

function switchColumns(){
    const makeSwitch1 = document.getElementById('column1');
    document.getElementById('column2').appendChild(makeSwitch1);

    const makeSwitch2 = document.getElementById('column2');
    document.getElementById('column1').appendChild(makeSwitch2);
}

Method 1:
I tried to import the .js file that contains the function.
Nothing is happening after clicking “Switch”.

Method 2:
Using onClick within a tag.

<div className="switch" id="switch_id" onClick={this.switchColumns}>Switch</div>

I get a couple of errors,

Uncaught TypeError: Cannot read properties of undefined (reading 'switchColumns')
The above error occurred in the <index> component:

Useref returning an error when switching view

I have an component with an useEffect method inside. And inside this useEffect method, there I created a useRef to handle some scroll effects and animations. Particularly, the const ref = useRef(null); . It works fine, however, upon switching views where this ref is not being used, it gives an error. Please see below code and picture:

  const ref = useRef(null);
  const hiddenRef = useRef(null);

  useEffect(() => {
    const handleScroll = () => {
      let scrollPosition = window.pageYOffset;
      let windowSize = window.innerHeight;
      let bodyHeight = document.body.offsetHeight;

      let diff = Math.max(bodyHeight - (scrollPosition + windowSize));
      //diff*100/scrollposition
      let diffP = (diff * 100) / (bodyHeight - windowSize);

      ref.current.style.transform = `translateY(${-diffP}%)`;

      window.pageYOffset > 5
        ? (hiddenRef.current.style.display = 'none')
        : (hiddenRef.current.style.display = 'block');
    };

    window.addEventListener('scroll', handleScroll);

    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

enter image description here

I believe I am supposed to unmount the ref, however, when I do this it does not work. Please see below:

 return () => {
    window.removeEventListener('scroll', handleScroll);
    ref.current = null;
}

Anyone know what it could be? Thanks

How can I change the attribute of a button in a specific html file from a javascript code in a different file

The html file contains

<div class="dialog-frame" style="width: 450px;">
  <div class="dialog-border">
    <div class="dialog-header" bind="dialogHeader"></div>
    <div class="dialog-body" bind="dialogBody">
      <div class="grid-layout layout-tighter"><table>
        <tr>
          <td colspan="2"><span bind="or_views_searchFor"></span> "<span bind="cellTextSpan"></span>"</td>
          <td><input bind="input" /></td>
        </tr>
        <tr>
          <td width="1%"><input type="radio" name="cell-recon-search-for-match-mode" checked="true" bind="radioSimilar" id="$cell-recon-search-match-similar" /></td>
          <td><label for="$cell-recon-search-match-similar" bind="or_views_matchOther"></label></td>
        </tr>
        <tr>
          <td width="1%"><input type="radio" name="cell-recon-search-for-match-mode" bind="radioOne" id="$cell-recon-search-match-one" /></td>
          <td><label for="$cell-recon-search-match-one" bind="or_views_matchThis"></label></td>
        </tr>
      </table></div>
    </div>
    <div class="dialog-footer" bind="dialogFooter">
      <button class="button button-primary" bind="okButton"></button>
      <button class="button" bind="newButton"></button>
      <button class="button" bind="clearButton"></button>
      <button class="button" bind="cancelButton"></button>
    </div>
  </div>
</div>

From my javascript file how do I change the checked attribute of radio button id=”$cell-recon-search-match-similar”

I am writing a hangman style program but am having trouble checking if more than one character has been entered and the set word is guessed

I am using a while loop to check if the number of guesses is less than 10 and once 10 guesses has been made it will prompt you one last time to input the whole answer not just individual characters. I know you can use .length to check the length of the input but I am not sure how to check for a particular input of characters. I have already tried doing “(guess.length === phrase)” which is the prompt variable on the left and the word variable on the right.

Here is my code.

function myGame()
{
var name = prompt("Please enter your name");
document.getElementById("user_name").innerHTML = "Welcome " + name + " to Wheel of Fortune";    
const d = new Date();
document.getElementById("today_date").innerHTML = d;    

  var count = 0;
  phrase = "parseint";
  var lgth = phrase.length; var checkWin = false; var correct_guess = false; var guess;
  var numCols = lgth; new_word = ""; var crazyWord = ""; var new_word = ""; crzLgth = crazyWord.length;
  for (var cols = 0; cols < numCols; cols++)
  document.getElementById('wheel_game' + cols).innerHTML = ("/ ");
  document.getElementById('hWord').innerHTML = "The word was " + (phrase);  
  while (checkWin === false && count < 10)
  { 
    correct_guess = false;
    guess = prompt("Guess a letter");
    for (var j = 0; j < lgth; j++)
    {
      if (guess === phrase.charAt(j))
      {
        correct_guess = true;
         count = count + 1;  
        document.getElementById('wheel_game' + j).innerHTML = guess;        
        for (var nw = 0; nw < lgth; nw++)
        crazyWord = crazyWord + (document.getElementById('wheel_game' + nw).innerHTML);        
      }
      
      new_word = crazyWord.substr((crzLgth - lgth), lgth);
     
      checkWin = checkWord(phrase, new_word);      
    }
    
    if (checkWin === true)
    { 
      document.getElementById("result").innerHTML = ("You win!");
    }
    else if (checkWin === false)
    { 
      document.getElementById("result").innerHTML = ("You Lose");    
      if (correct_guess === false)
      count = count + 1;  
      if (count === 10) 
      {
        guess = prompt("One last chance to guess the word");    
      }
      else if (guess.length === phrase) {
        checkWin = true;
        document.getElementById("result").innerHTML = ("You win!");
      } 
    }
}
  
  function checkWord(phrase, otherWord)
  {
    var cleanWord;
    cleanWord = otherWord;
    if (phrase === cleanWord)
      return true;
    else
      return false;
  }
}

HTML.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Game of Hangman">
<title>Chapter 7 program</title>
</head>
<body>
    <h1>Welcome player</h1>    
    <p> Click to begin </p>
    <p>
    <input type="button" value="Begin" onclick="myGame();" />    
    </p>    
<p id="user_name"> </p> <br>
<p id="today_date"> </p> <br>
<p id="catagory"> </p> <br>

      <div id="wheel_game0"></div> <br>
      <div id="wheel_game1"></div> <br>
      <div id="wheel_game2"></div> <br>
      <div id="wheel_game3"></div> <br>
      <div id="wheel_game4"></div> <br>
      <div id="wheel_game5"></div> <br>
      <div id="wheel_game6"></div> <br>
      <div id="wheel_game7"></div> <br>
      <div id="wheel_game8"></div> <br>
      <div id="wheel_game9"></div> <br>
      
      <div id="hWord"><p></p></div>
      <div id="result"><p></p></div>
    
<script src="myScript.js"></script> 
</body>
</html>