jQuery Element Selection Discussion

Funny, I like it. Thanks Antay, for sharing. You have some skills

Nice Stuff Ivan. Learned new dimensions to build webpages:-)

Great examples of using JQuery. Tnx for all the examples guys.

Hi all
using the jQuery selectors and program below, a way to fade or slide toggle effects with time can produce some cool things,

Change from . $(".test").hide(); to $(".test").fadeOut(500); or $(".test").slideToggle(500);

This is a great site
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>


<script>
$(document).ready(function(){
  $("button").click(function(){
    $(".test").hide();
  });
});
</script>
</head>
<body>

<h2 class="test">This is a heading</h2>

<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Click me</button>

I attempted jQuery by coding a search for recipes without luck
/

Recipe
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://code.jquery.com/jquery-latest.min.js"></script>

Recipes

<body>
  <form onsubmit="recipe(); return false;"
    <input autocomplete= "off" autofocus id = "cookBookName" placeholder="cookBookName" type="text"/>
    <input type="submit" value="get Recipe"/>

  </form>

  <script>

// Get recipes via JSON
function cookBookName()
{

     var url = '/recipe?cookBookName=' + $('#cookBookName').val();
     $.getJSON(url, function(data){
       $("#recipe").onsubmit('Recipe from + data.https://www.allrecipes.com');
       $("#cookBookName").val("");
       data.preventDefault();

     });


   }
   </script>
</body>

@filip

The main question I’m left with after experimenting further with jQuery is:

When we use jQuery, are we free to add other valid JavaScript syntax within the same jQuery code blocks, in order to express things we can’t find alternative jQuery syntax for?

For example, in my program code below, I want to convert a number expressed as a string to a number data type. The number is retrieved from an HTML <input type="range"> element using the jQuery .val()  method, to then use it as the speed parameter in the jQuery  .toggle().fadeToggle()  and  .slideToggle()  effect methods. This speed parameter needs to be a number data type, but it’s retrieved as a string. I’ve performed the conversion by wrapping the jQuery expression with either the  Number()  or the  parseInt()  global function, as follows:

Number($('#speed').val())
// or
parseInt($('#speed').val())

I’d be interested to hear any comments about the use ofNumber()vparseInt()

Further to a couple of posts in this thread about other effects which can be achieved with jQuery, I’ve written a program (code below) to visually demonstrate the differences between hide/show, fade in/out and slide down/up. I’ve used a default speed of 3000 milliseconds, which is slow enough to clearly show these differences. For further experimentation, the default speed can be altered using a slider control. Each position allowed on the slider either increases or decreases the speed by 500 milliseconds (range: 0 to 5000).

The jQuery code in the program uses both  #id  and  .class  selectors, and I also experimented with one of the more exotic jQuery selectors element:eq(index) which enables each of the HTML  <button>  elements to be individually selected according to their order within the program.

What follows is the separate (i) jQuery/JavaScript code, (ii) HTML code, and (iii) CSS code, for my program.
I have the jQuery/JavaScript code and the CSS code within the  <head>  of my HTML document, wrapped in  <script>  and  <style>  tags respectively.
The HTML code is for the  <body>  of the document.
If you want to run the program, you will also need to add the following HTML code:

  • <!DOCTYPE html>
  • <html>  and  <head>  opening and closing tags
  • a  <title>  element
  • additional  <script>  opening and closing tags referencing the jQuery library.
<!--     (i) jQuery/JavaScript code     -->

<script>
  $(document).ready(function() {
    $('button:eq(0)').click(function() {
      let effectSpeed = parseInt($('#speed').val());
      $('.effect').toggle(effectSpeed);
    });
    $('button:eq(1)').click(function() {
      let effectSpeed = Number($('#speed').val());
      $('.effect').fadeToggle(effectSpeed);
    });
    $('button:eq(2)').click(function() {
      let effectSpeed = Number($('#speed').val());
      $('.effect').slideToggle(effectSpeed);
    });
  });
</script>

I’d be interested to hear if anyone knows how to make the above jQuery/JavaScript code more succinct by avoiding having to repeat the statement  let effectSpeed = Number($('#speed').val());  three times — once in each of the  .click(function())  code blocks. So far, my research and experimenting with this has led me to observe the following:

  • If the statement is placed (only once) before the three  .click(function())  code blocks, then the speed parameter no longer changes when the slider control is adjusted.
  • I think a possible solution might involve using the jQuery  .change()  method on the  
    <input id="speed">  element, but I can’t find a way to integrate it successfully.
<!--     (ii) HTML code     -->

<body>
  <h1>Effects Tester</h1>
  <label for="speed">Set speed (milliseconds)&emsp;&emsp;0</label>
  <!-- <input type="range"> creates a slider control. 
       The default speed value is set using the value attribute.
       The speed value can then be changed by adjusting the slider control. -->
  <input id="speed" type="range" value="3000" min="0" max="5000" step="500">
  <label for="speed" >5000</label>
  <button>Click to hide or show</button>
  <button>Click to fade in or fade out</button>
  <button>Click to slide down or slide up</button>
  <div class="effect"><span>Test panel</span></div>
  <div class="text">
    <p>This text below the test panel is to see how this part of the page
       moves up and down depending on the movement of the test panel.</p>
  </div>
</body>
<!--     (iii) CSS code     -->

<style>
  body {
    margin-top: 0;
    max-width: 670px;
  }
  h1 {
    display: inline-block;
    margin-right: 90px;
  }
  button {
    margin: 0 20px 30px 0;
    padding: 10px 15px;
    font-size: 14px;
  }
  .effect {
    padding: 150px 0;
    text-align: center;
    font-size: 75px;
    background-color: cornflowerblue;
    color: darkblue;
  }
  .text {
    padding: 5px 15px;
    background-color: lightblue;
  }
  #speed {
    vertical-align: sub;
  }
</style>

Thanks for this! It got me doing some further research. I’m not sure if you also came across this, but there is another keyboard event property  .key  which returns a string of the key pressed — or to be precise, of the actual character entered (including control characters) — which in this case is 'Enter' . Using this (instead of  .keyCode )  would change the  if condition in your code to:

if (e.key == 'Enter')

Here is a link to the W3Schools page about this  .key  property.

Interestingly, on the W3Schools page about the  .keyCode  property, it says that using .key  is recommended instead of  .keyCode   and the other alternatives:  .which  and  .charCode  (browser support permitting). It also indicates that using  .keyCode  with the  onkeypress  event isn’t supported in the Firefox browser; however, it works fine in my Firefox browser (version 71.0) with the jQuery  .keypress()  event method.

I’ve also found out that there are two different sets of Unicode values: char codes and key codes.

This link in your post is to a list of key codes.

Each key on the keyboard (as opposed to each character) has a separate key code (a number). However, using  .keyCode  will only return key codes if used with the jQuery  .keydown()  or .keyup()  event methods. Also, if you have a non-English-language keyboard, the key-code numbers, although representing the same key position (I think), will actually correspond to different characters because of different keyboard layouts for different languages. For example, I have a Spanish keyboard and key code 219 is returned by my single quote key, not the open bracket/parenthesis key as indicated on the list you’ve linked to.

On the other hand, if, as in your code,  .keyCode  is used with the jQuery  .keypress()  event method, it will actually return char codes instead of key codes. Each ASCII (extended to UTF-8) character has its own char code (also a number), so entering a lower case ‘a’ will return a different char code (97) to entering an upper case ‘A’ (65). Letters with accents and other diacritical marks, and other lesser used symbols, also have their own char code number (e.g. ç returns 231, ¿ returns 191, and
£ returns 163).

Upper case letters and digits 0 to 9 have the same numbers for both key code and char code, as do some of the control keys/characters. However, out of these control keys/characters, only Enter seems to return the number 13 as both key code and char code — and so works with  .keypress()  as well as with  .keydown()  and  .keyup() . Others, such as Tab and Escape, only seem to return key codes — and so I can only get them to work with .keydown() and .keyup() .

See this W3Schools page for a list of the ASCII characters and their corresponding char codes.
See this W3Schools UTF-8 Reference with links to more exhaustive lists of characters and their corresponding char codes.

It seems to me that, browser permitting, the advantages of using  .key   are:

  1. It can be used with all three jQuery keyboard event methods:
    .keypress().keydown()  and  .keyup()
  2. Referencing the character to be returned (or the key to be pressed) with a string, instead of a number (from one of two different sets), is much easier for the developer, leads to less confusion, and makes the code easier to read.

At the risk of confusing things even more, the jQuery API documentation https://api.jquery.com/category/events/keyboard-events/ recommends using the normalised
.which  event property to retrieve both key codes and char codes. However, I can’t actually find any practical difference or advantage of using  .which  instead of  .keyCode .


This is my final version of the code:

$('#textInput').keypress(function(event) { 
  let display = $(this).val();                  
  if (event.key === 'Enter') alert(display);
}); 

The keyword  this  references the current HTML element:
 — the text box  <input id="textInput" type="text">

Wow! You are really hard at work, I love it!

When we use jQuery, are we free to add other valid JavaScript syntax within the same jQuery code blocks, in order to express things we can’t find alternative jQuery syntax for?

Yes, you can mix syntax without any problem. The only thing you have to be cautious about is not to confuse Javascript objects for jQuery objects. So for example, when you are using a jQuery to find an element with $(’#selector’), that will give you a jQuery object. That jQuery object has methods like .val().

If you are using the pure javascript function getElementById(“selector”), that will give you a so called vanilla Javascript object. If you try to run .val() on that object it will fail because it doesn’t have any method with that name. The method .val() is a jQuery function that only exists on jQuery objects.

But apart from that there is no problem mixing the two.

1 Like

OK, that makes sense that you can only call jQuery methods on jQuery objects. However, once that jQuery method has returned a value, we can then manipulate that value with either syntax, like I did with …

… to convert a number expressed as a string (returned from the .val() method, in this particular case) to a number data type — is that correct?

Yes, that’s correct!

1 Like

OMG! You gys are such swats. I am getting the idea in principle but also overwhelmed by the immensity of the task ahead of me. When do I get to build my crypto! :dizzy_face:

SyntaxEditor Code Snippet

function runThis(){ alert(“Button onclick Event”); } $(document).ready(function(){ $(’#newButton’).click(function(){ alert(“Button #id.click”); }); $(’#myTextButton’).click(function(){ var myText = $(’#myText’).val(); alert(myText); }); });

I wanted to make a simple paragraph hide/show button as a simple test, but struggled a tiny bit with reading the current state of the .show and .hide actions for an IF ELSE statement, and then found the .toggle function. I then wanted to make the paragraph fade in/out with the above request, and then found the .fadeToggle function!

Javascript, it just keeps surprising me and puts a BIG smile on my face lol!

3 Likes

Amazing way to become more a robust programmer with the use of jQuery.

jQuery selectors allow you to select and manipulate HTML element(s).

jQuery selectors are used to “find” (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It’s based on the existing CSS Selectors, and in addition, it has some own custom selectors.

All selectors in jQuery start with the dollar sign and parentheses: $().
The #id Selector $("#test")
The .class Selector $(".test")
etc…

1 Like

Alert, after clicking the button (version 1)

<html>
  <head>
    <title>
      Click the button!
    </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>
  </head>
  <body>
    <input type="text" id="ourInput">
    <button id="ourButton">Click me</button>
    <script>
    $("#ourButton").click(function(){
        alert($("#ourInput").val());
    });
    </script>
  </body>
</html>


In this working example, the user first inputs a string and then clicks the button. After clicking the button the content of the textbox is shown in the alert. But this only works, if the textbox and the button are defined before the script. If you change the order of definition in the body, the website will not work anymore:

  <body>
    <script>
    $("#ourButton").click(function(){
        alert($("#ourInput").val());
    });
    </script>
    <input type="text" id="ourInput">
    <button id="ourButton">Click me</button>
  </body>

The version right above does not work, because the textbox and the button are “not known” to the script yet. However you can solve this problem by embedding the content of the script between the curly brackets of the following function:

$(document).ready(function(){ Put the content of the script here! }

In the following example this has been done! One can even move the script to the head tag. In this example the script will wait, until the HTML document is ready and therefore it works well!

Alert, after clicking the button (version 2)

<html>
  <head>
    <title>
      Click the button!
    </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>
    <script>
    $(document).ready(function(){
      $("#ourButton").click(function(){
          alert($("#ourInput").val());
      });
    });
    </script>
  </head>
  <body>
    <input type="text" id="ourInput">
    <button id="ourButton">Click me</button>
  </body>
</html>


Since I am also a beginner in JavaScript, you can correct me, if there is some mistake. But maybe this post will be helpful to someone, because I also wondered why the $(document).ready(function(){} is used in so many examples. Hopefully this post can save somebody some time!

1 Like

@ivan
@Fabrice

Dynamic List - User Adds Elements

Javascript Next Level

Ivans solution for the assignment


The assignment in the last video had been to develop a website that has a textbox and a button. By clicking the button the text in the textbox which is another fruit should be added to the list automatically. Ivan added the fruitText from the input box to the existing list fruits with the push method. But the problem was that the website did not update the changes. So Ivan decided to redraw the list of fruits by inventing the redrawList function. But trying this approach the whole new list had been added to the old list leading to double entries in the list. So the last change to the code was the deletion of the list with the statement list.html(""); in the redrawList function.

I thought why not simply use the appendTo(list) method once again?
Here is my proposal:

      $("#addFruitButton").click(function(){
        var myNewFruit = $("#fruitTextInput").val();
        $("<li/>").text(myNewFruit).appendTo(list);
      });

The click listener of the addFruitButton gets the text from the inputbox and stores it into the variable myNewFruit with the following command:
var myNewFruit = $("#fruitTextInput").val();

Now the only thing to be done is call the appendTo(list) method, passing the value of myNewFruit as an argument:
$("<li/>").text(myNewFruit).appendTo(list);

And for your reference the entire code below:

<html>
  <head>
    <title>
      Great website
    </title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>

  </head>
  <body>
    <h1>My favorite fruits</h1>
    <ol id=fruitList>
    </ol>
    <input id="fruitTextInput" placeholder="Write fruit" type="text">
    <button id="addFruitButton">Add fruit</button>

    <script>
      fruits = ["Apple", "Orange", "Banana", "Pineapple"];

      var list = $("#fruitList");

      //Adding list items of existing list
      $.each(fruits,function (index,value){
        $("<li/>").text(value).appendTo(list);
      });

      //Adding new fruit list item from textbox
      $("#addFruitButton").click(function(){
        var myNewFruit = $("#fruitTextInput").val();
        $("<li/>").text(myNewFruit).appendTo(list);
      });

    </script>
  </body>
</html>

But in the solution above I used the appendTo(list) method twice. So I decided to move this into a function. Here is my second proposal:

<html>
  <head>
    <title>
      Great website
    </title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
    </script>

  </head>
  <body>
    <h1>My favorite fruits</h1>
    <ol id=fruitList>
    </ol>
    <input id="fruitTextInput" placeholder="Write fruit" type="text">
    <button id="addFruitButton">Add fruit</button>

    <script>
      fruits = ["Apple", "Orange", "Banana", "Pineapple"];

      var list = $("#fruitList");

      //Adding another fruit to the list
      function appendFruitToList(anotherFruit){
        $("<li/>").text(anotherFruit).appendTo(list);
      };

      //Adding list itema of existing list
      $.each(fruits,function (index,value){
        appendFruitToList(value);
      });

      //Adding new fruit list item from textbox
      $("#addFruitButton").click(function(){
        var myNewFruit = $("#fruitTextInput").val();
        appendFruitToList(myNewFruit);
      });

    </script>
  </body>
</html>

After these thoughts I created the reuseable function appendFruitToList. It is called twice. One time for creating the list entries of the existing list with appendFruitToList(value) and one time for adding the new list element with appendFruitToList(myNewFruit).

2 Likes

I have a question regarding my solution to the getting user input task.
My solution:

    <script>
      $("#button").click(function(){
        alert(inputfield.value);
      });
    </script>

My solution works perfect, I only want to know what is the advantage/disadvantage of Ivans solution and mine? What would you prefer in real world applications and why? Ivan is using jQuery for getting the value of the input field and he declares a variable to save the it. Of course, if you have to use the input field several times it makes sense to do it. Maybe someone has some interesting information why Ivan or mine solution is better.

Was able to get a solution:

Get the value to show Show Value
1 Like

It’s cool, but for some reason, my browser doesn’t clear the input box when I refresh it. Do you have any idea why that is?

1 Like