Category : HTML

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

Adding tabbed panels to Bootstrap – No jQuery

A great little piece of functionality built into Bootstrap is the ability to clear up some screen space using panels cascaded behind each other in tabs.  The best part is, it’s super easy to implement.

Here’s the code:

<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
    <li class="active"><a href="#tab1" data-toggle="tab">Tab 1</a></li>
    <li><a href="#tab2" data-toggle="tab">Tab 2</a></li>
    <li><a href="#tab3" data-toggle="tab">Tab 3</a></li>
    <li><a href="#tab4" data-toggle="tab">Tab 4</a></li>
    <li><a href="#tab5" data-toggle="tab">Tab 5</a></li>
</ul>
<div id="my-tab-content" class="tab-content">
    <div class="tab-pane active" id="tab1">
        <h1>Tab 1</h1>
    </div>
    <div class="tab-pane" id="tab2">
        <h1>Tab 2</h1>
    </div>
    <div class="tab-pane" id="tab3">
        <h1>Tab 3</h1>
    </div>
    <div class="tab-pane" id="tab4">
        <h1>Tab 4</h1>
    </div>
    <div class="tab-pane" id="tab5">
        <h1>Tab 5</h1>
    </div>
</div>

The above code will leave you something looking like this:

bootstrap-tab-loader

Feel free to use, copy and modify this code as you need to.

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

Disable a dynamically created Bootstrap button onClick

There might be times when you need to produce a dynamic list of things that you don’t want to happen twice, like updating the status of something, but in particular only wanting to act as a single use event on that line.  You can use jQuery to send a post request to perform the action, but it’s handy to be able to disable the button as well.  Doing so will guarantee the end user won’t be able to click again before the page/div/section refreshes,  even if you do update those above in the background.

If you have a button producing loop like this:

while([something happens to produce $row(for example)]){
  <button class="btn btn-default btn-xs" id="dynamicBtn'.$row['id'].'" onClick="buttonFunction(this.id)>Disable Me</button>
  <button class="btn btn-default btn-xs" id="dynamicBtn'.$row['id'].'" onClick="buttonFunction(this.id)>Disable Me</button>
  <button class="btn btn-default btn-xs" id="dynamicBtn'.$row['id'].'" onClick="buttonFunction(this.id)>Disable Me</button>
  <button class="btn btn-default btn-xs" id="dynamicBtn'.$row['id'].'" onClick="buttonFunction(this.id)>Disable Me</button>
}

Ignore the weird formatting on this thin blog page.

onClick calls a function and takes the ID value of the row to send to the said JavaScript method.  This, in turn, can then be used to disable (or anything else you need it to) the buttons on that line.  It’s quite generic actually and can be tailored for many different uses if you need it to do specific things to anything with the ID you are sending.

The JavaScript looks like this:

function buttonFunction(rowID) {
  $('#dynamicBtn'+rowID).prop("disabled", true);
  // Then do anything you need to do in the background if required
}

If the “do something in the background” is performing an AJAX request, you can make part of the “success” attribute re-enabling the button and giving an appropriate error message if something goes wrong.

You could also do this backwards and make disabling the button part of the AJAX success, but it leaves open the option of clicking several times if the request takes a few seconds to process.

It’s not good practice to be using jQuery lower than version 1.6 at the point of writing this, however, if you do, then switch out the newer “prop” method for “attr” to achieve the same thing.

Share this post:
read more