Category : jQuery

Get the values of an array of radio buttons – jQuery

Getting the value of a group of radio buttons is relatively straightforward, but what happens if you have more than one set?

I’ll start with a simple example of how to gather the data from a single set of radio buttons.

We’ll use this as our working example:

<div class="form-group">
  <div class="form-check form-check-inline">
    <input class="form-check-input checkMe" type="radio" name="amIChecked" value="yes">
    <label class="form-check-label" for="amIChecked">Yes</label>
  </div>
  <div class="form-check form-check-inline">
    <input class="form-check-input checkMe" type="radio" name="amIChecked" value="no">
    <label class="form-check-label" for="amIChecked">No</label>
  </div>
</div>

 

The jQuery to gather these fields would look something like this:

<script>
  jQuery(".checkMe").change(function(e) {
    e.preventDefault();
    const result = $("input[name='amIChecked']:checked").val();

    alert(result);

  })
</script>

In the above code, we are listening for a change event on the “checkMe” class.  At this point, we have asked the browser to provide the value of the input with the group name of “amIChecked”.

But what would happen if we were to produce a list, all ending in radio buttons?  If we adopted the above code, we would end up with only the result of the last set of radio buttons that the browser produced as it would keep re-attaching itself to the elements as they are rendered.  In this situation, we need to add something unique to each one.

I will assume at this point the list that your app is producing is being produced by a call to a database or similar.  If it isn’t and you just have a hard-coded list, this can still apply.

We need to take another approach to this to get this to fire correctly.  If you have been trying to do this with a similar method, then you will realise that applying the above method using a tweak of the above will produce hit and miss results.

The best way to approach this now is with a function.

Modified HTML:

<form id="{{ $thisRow->id }}">
  <div class="form-group"> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id="{{ $thisRow->id }}" name="amIChecked" onclick="clickedRadio('{{$rowID->id}}','yes')"> 
      <label class="form-check-label" for="amIChecked">Yes</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }}  name="amIChecked" onclick="clickedRadio('{{$rowID->id}}','no')"> 
      <label class="form-check-label" for="amIChecked">No</label> 
    </div> 
  </div>
</form>

I’m using the amazing Laravel framework in my project, so my ID is being produced in the Blade template using Laravels {{ }} syntax.  <?=$row->id;?> if you’re using vanilla PHP would be fine too.

You may notice I have also I have added <form> tags to each of the iterations in the loop.  This is because browsers will tend on only default the “checked” option (if you are using it) to the last iteration if everything has the same name value.  By adding <form> tags with a unique name, the browser treats all iterations as a single form.

Our function sends the row ID and the value to the jQuery for you to do with as you need.  With this in mind, there is no need to have the value=”” tags anymore, as they have been hardcoded in.

Now the modified jQuery:

<script> 
function clickedRadio(rowID, value)
    {
        alert(rowID + " : " + value);
     } 
</script>

With every click you should now get a row ID from your database (or whatever unique identifier you have chosen), and its value.  In this case, it will be yes or no, but it could be cats/dogs, on/off etc.

You aren’t limited to just two radio buttons using this method either.  This can be expanded to multiple values by just adding them in.

For example, this would be just as effective:

<form name="{{$rowID->id}}">
  <div class="form-group"> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','1')"> 
      <label class="form-check-label" for="userValue">Yes</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','2')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div>
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','3')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','4')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div> 
    <div class="form-check form-check-inline"> 
      <input class="form-check-input checkMe" type="radio" id={{ $thisRow->id }} name="userValue" onclick="clickedRadio('{{$rowID->id}}','5')"> 
      <label class="form-check-label" for="userValue">No</label> 
    </div> 
  </div>
</form>

Have fun!

Share this post:
read more

Getting the ID of draggable and droppable elements – jQuery

jQuery’s drag and drop functionality is fantastic and adds excellent interactivity to your web application.  However, it can be a little confusing, so here are some straightforward examples that should get you off to a flying start when venturing into the world of drag and drop.

First, we need a few things to move around, so let’s create some:

<div id="div_01" class="draggable">Div 01</div>
<div id="div_02" class="draggable">Div 02</div>
<div id="div_03" class="draggable">Div 03</div>
<div id="div_04" class="draggable">Div 04</div>
<div id="div_05" class="draggable">Div 05</div>

You’ll need to get these in the context of your web page.

Next, we need somewhere to drop them:

<div id="dropzone_1" class="dropzone" style="height:100px;width:100px;border:1px solid black"></div>
<div id="dropzone_2" class="dropzone" style="height:100px;width:100px;border:1px solid black"></div>
<div id="dropzone_3" class="dropzone" style="height:100px;width:100px;border:1px solid black"></div>

I’ve used inline styles in the example above in case you are copying and pasting into a test HTML page of your own.  Inline styling isn’t great in a production environment; a separate style sheet is always better.  I’ve also assumed, that you have loaded the jQuery / jQuery UI version[s] of your choice onto the page by this point as well.

Making these elements draggable and droppable is easy.  Just add a function that covers both scenarios and then build upon them.

$(function () {
    $(".draggable").draggable();
    $(".dropzone").droppable();
});

At this point, you should be able to grab you divs and move them around the page.  They won’t do anything aside from move around the page, but it’s quite a novelty the first time it happens successfully!

It’s at this point the language used by jQuery can be a little bit confusing.  “Draggable” is obvious; it is something that can be dragged around the screen, its when you get to “droppable” that people sometimes run into confusion.  “Droppable” suggests you are dealing with something that once you start dragging around, is then available to be dropped, however, this isn’t the case.  “Droppable” by jQuery’s definition is the area that you drop a draggable.  The draggable itself, contains the drop event, whereas the droppable is just a static place your draggable gets dropped.

Confused yet? Don’t be; it’s effortless when you see it broken down.

Doing something with my draggable and droppable.

Take a look at this extended version of the code snippet above.  What you see below is taken directly from one of my live projects, so will need to be customised to suit your project:

$(function () {
    $(".draggable").draggable(
        {
            start:
                function (event, ui) {
                    $(this).css("z-index", 10);
                }
        }
    );
    $(".dropzone").droppable({
        drop: function (event, ui) {

            const dropZoneID = $(this).attr('id');
            const droppedItemID = ui.draggable.attr("id");

            /* 
             Do something with your newly gathered information
             */
        }
    });
});

So what is going on in the code above?  Let’s start with the draggable.  There are various events associated with the draggable.  Notably, these are start, stop and drag.  In the example above I’ve used the start event to bring the item, I’m dragging to a z-index of 10.  With my Bootstrap projects, I’ve found this handy to ensure the thing I’m dragging around remains at the top.  If I don’t set this index with Bootstrap, the draggable can end up going behind some of the other elements.

You can find a full reference to jQuery draggable here.

Lovely, but the exciting part comes when you drop these draggable.

The two critical pieces of information you need when dealing with draggable items and dropzones [and this may seem obvious] are, what you’ve dropped and where you’ve dropped it.  This is achieved using the “drop” event inside the droppable.  Here, I have created two constants [variables are also fine] that will gather this information.

A great way to visualise this if you are starting out with these is to add a test div, so you can see what’s happening.

Create a div, like this:

<div id="testDropDiv"></div>

Then in your code, add the following:

$(".dropzone").droppable({
        drop: function (event, ui) {

            const dropZoneID = $(this).attr('id');
            const droppedItemID = ui.draggable.attr("id");

            $("#testDropDiv).empty()
                     .append("I've just dropped div with ID: " + droppedItemID + " Onto: " + dropZoneID);

        }
    });

Which should then update each time you drop one of your draggable onto a dropzone.

The reference for jQuery droppable is available here.

I hope that gives a little bit of an insight into jQuery’s draggable and droppable.  This short introduction has only just scratched the surface of what is achievable.  I would recommend you have a look at the jQuery UI website to see some more examples.

Share this post:
read more

Create a character countdown for text inputs and textarea’s using jQuery

I think it may have been Twitter that first pioneered the use of the text character countdown years ago.  I could be wrong, maybe they just popularised it, but either way, it is a convenient way of keeping user inputs to a length that is acceptable to your site.

I’m not sure that this is the place to mention it, but I do still find myself writing shorter tweets, despite the limit raise a while ago.

There are going to be three main parts to this:

  • Create an HTML form that needs the input characters kept in check.
  • Write some jQuery code to keep an eye on what is happening when the user’s types.
  • Style a little blank <span> underneath the input to show the user how they are getting on.

For those of you that read regularly, you will know I am a big Bootstrap fan (hark the Twitter reference again), so the form has some Bootstrap elements to it.  This form will work just as well without the BS references.

Create the input:

<label for="myInput"><strong>My Limited Input:</strong></label>
<input class="form-control" type="text" id="myInput" maxlength="50">
<span id="showCountdown" class=limits"></span>

I’ve used the HTML “maxlength” in the above snippet so that the browser automatically restricts any more inputs at that point.  The HTML “maxlength” has nothing to do with the character countdown.  “maxlength” is universally accepted on most browsers except for the ancient, so you shouldn’t run into many [if any] compatibility problems.

Just for curiosities sake, the default value for maxlength is 524288.

Next, we need to add some jQuery to do the counting and append the <span> underneath the input:

$('#myInput').on("keyup change", function ()) {

  const max = 50;
  const len = $(this).val().length;

  if (len >= max) {
    $('#showCountdown').text("No more room ...");
  } else {

    const char = max - len;
    $('#showCountdown').text(char + ' characters remaining');
  }
});

So what’s happening here?

The browser is looking for either a keyup event or a change event occurring in the input.  Change is handy because, in the majority of cases, the will also catch the user if they try and paste something into the box.  When the event is detected, it counts the length of the string inside the input.  It then compares it to the max variable we’ve included and deducts one from the other.

After evaluating whether the length of the input is smaller (by x number) or equal to the max value, it adds an appropriate message into the empty span underneath the box.

Now a little styling:

<style>
#showCountdown {
  font-size: 12px;
  color: #3399ff
}
</style>

You can style this in any way you wish.

Below is an example of this text input in action on a site I’m working on at the moment,  Although I think I used dodgerblue as the colour:

 

 

Share this post:
read more

Getting the value or text of an HTML attribute using jQuery

Grabbing attributes to use in your JavaScript is often handy.  HTML attributes can be used to send various options to your script or attributes used for multiple switches to control different elements of what you are doing.

You can use HTML attributes on their own, or grab them from specific elements with this.

If you are using a standalone element, such as:

<button class="btn btn-outline-success btn-sm buyButton" value="profile" customTitle="Profile Upgrade">BUY</button>

You can use a specific selector:

const itemTitle = $('.buyButton').attr('customTitle');

If you are using multiple selectors, then you can grab the values from the button you want, when using onClick, for example, in a similar way.

So if you have:

<div class="col-sm-2">
    <button class="btn btn-outline-success btn-sm buyButton" value="profile" customTitle="Profile Upgrade">BUY</button>
</div>
<div class="col-sm-2">
    <button class="btn btn-outline-success btn-sm buyButton" value="listing" customTitle="Listing Upgrade">BUY</button>
</div>
<div class="col-sm-2">
    <button class="btn btn-outline-success btn-sm buyButton" value="highlight" customTitle="Highlight Listing">BUY</button>
</div>

(I’ve made some of these up, and some of the bits are unnecessary, like the DIV’s, they are just in the project I’m working on)

So if you want to get the customTitle attribute to use in your logic somewhere, use:

$(".buyButton").on('click', function(e) {
    e.preventDefault();
    const customTitle = $(this).attr('customTitle');
})

 

Share this post:
read more

Get the value of selected radio buttons – jQuery

If you need to get the value of a selected radio button dynamically, to send for processing via an AJAX call for example, then the following is a great way to achieve this.

The general methodology is to give all of the radio options a generic class that can be used to trigger the onchange event. Then, grab the value of the radio button that has been selected and use it in your processing script.

In the below example, we use the “class” to define the group, the “name” to define what we are selecting, and the “value” to determine what is then sent to the processing script.

The radio buttons:

<div class="row">
  <div class="col-sm-6">
    Option 1
  </div>
  <div class="col-sm-6">
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option1" value="show" checked>Show
      </label>
    </div>
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option1" value="hide">Hide
      </label>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-sm-6">
    Option 2
  </div>
  <div class="col-sm-6">
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option2" value="show" checked>Show
      </label>
    </div>
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option2" value="hide">Hide
      </label>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-sm-6">
    Option 3
  </div>
  <div class="col-sm-6">
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option3" value="show" checked>Show
      </label>
    </div>
    <div class="form-check-inline">
      <label class="form-check-label">
        <input type="radio" class="form-check-input viewChange" name="option3" value="hide">Hide
      </label>
    </div>
  </div>
</div>

There’s a lot of Bootstrap 4 formatting in there as well, as this was taken from one of my live projects.  I have also used the values “show” and “hide”, as these are project specific, but you could add any values you require in here.

Then some JavaScript to do the actual work:

$(".viewChange").on("change", function(e){

    e.preventDefault();

    const option1status = $("input[name='option1']:checked").val();
    const option2status = $("input[name='option2']:checked").val();
    const option3status = $("input[name='option3']:checked").val();

    /*
    Do something with your now created constants
    */

});

 

This will produce the outputs you need to then do processing as you require.

Share this post:
read more

Stop jQuery ignoring the if/else conditions

You may or may not have come across this.  If you are using an AJAX call and have added an if/else statement to the success: parameter, and in particular have bound some actions to an element within those clauses, it can carry on and run the else, even if the if has been satisfied.

Example:

success: function(result) {

            if(result == "success")
            {
                window.location.replace('/somewhere_else');
            }
            else {
                $("#errorMsg").append(result);
            }

        }

This can be avoided if you terminate the jQuery with a false return.

Example:

success: function(result) {

            if(result == "success")
            {
                window.location.replace('/portal');
                return false;
            }
            else {
                $("#errorMsg").append(result);
            }

        }

It will halt the jQuery in its tracks, before it can do something odd.

This is observational behaviour and could well be something that I am doing that is causing this in the first place, so if it is, and somebody would be kind enough to point it out, I would be very obliged.

Share this post:
read more

JQuery is() and not() and isNot() :not()

Probably is() as confusing as it sounds.

Example is();

if($(this).is('.disabled){
    // Do something if the element is disabled
}
else {
    // Do something if the element isn't disabled
}

The assumption then is that the not() function is the opposite.  Sadly, this isn’t the case.  The is() function will return a Boolean value (true/false), however, the not() function is a filter and will return a specific set of elements.

So what is the opposite of is()?  It’s the same as PHP [and others], you just add an ! to reverse it:

if(!$(this).is('.disabled){ 
    // Do something if the element isn't disabled 
} else { 
    // Do something if the element is disabled 
}

 

 

Share this post:
read more

Disable and enable buttons (Bootstrap) using a jQuery extension

A nice easy way to disable and re-enable buttons [etc] in Bootstrap with a little extension to the jQuery library.

Add this into the js file, either a custom.js or the main jQuery class file.  Custom being better so it doesn’t get overwriten in the future.

jQuery.fn.extend({
    disable: function (state) {
        return this.each(function () {
            var $this = $(this);
            $this.toggleClass('disabled', state);
        });
    }
});

Then use like this:

$("#button").disable(true);
$("#button").disable(false);

 

 

 

Share this post:
read more

Only allow numbers to be entered in an HTML form text field

Sometimes, if you are adding say, a phone number into an input field, you don’t want people to enter letters.  This snippet contains a handy little regex to remove any non-number from an input as the user types.  It’s not foolproof, but it does the job.

Nice simple addition to forms to only allow letters in a text input field:

$("#yourInput").keyup(function()
    {
        if (/D/g.test(this.value))
        {
            // Remove the non-digits from the input
            this.value = this.value.replace(/D/g, '');
        }
    });

UPDATE (2018)

Given that this was a lazy post back when I wrote it, I’ve added a slightly updated version that will look for a change, and other inputs as well.  A few more event listeners will cover some of the users who may like to paste things into the box.

Remember, making forms look pretty before they are submitted it great, but it doesn’t replace proper server-side validation of the input at the other end.  If you are using a database, don’t just sanitise, prepare.

$("#yourInput").on("keyup paste change", function()) 
{ 
  if (/D/g.test(this.value)) 
  { 
    this.value = this.value.replace(/D/g, ''); 
  } 
});

 

Share this post:
read more

Get the value of a select dropdown using jQuery or JavaScript

Sometimes you just need to grab the value of the selected option with Javascript, or jQuery, if that is your flavour.

Something to bear in mind that confuses some people, is that the select options have two parts.  One of those parts is the value, as selected in the value=”” section, and the other is the text value that is displayed on the users browser.

Here’s how to get either the hidden value, or the text value with either method:

Good old JavaScript:

var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

jQuery:

$("#elementId :selected").text(); 
$("#elementId").val();

The element ID refers to the id of the selector, for example:

<select name="someName" id="elementID">
  <option value="[VALUE]">[TEXT]</option>
</select>

 

Share this post:
read more
1 2