Tag Archives: JavaScript

Ensure only a UK decimal value is added to a textbox – JavaScript

If you are adding a price, or a value to a textbox input, you may need to sanitise it.  This script will make sure that nothing is allowed in the box except for a decimal point and numeric values.  It will also ensure that there is only two numbers after the decimal place and that there can only be one decmial place.

$('#someTextInput').keypress(function(event) {
        var $this = $(this);
        if ((event.which !== 46 || $this.val().indexOf('.') !== -1) &&
            ((event.which < 48 || event.which > 57) &&
                (event.which !== 0 && event.which !== 8))) {
            event.preventDefault();
        }

        var text = $(this).val();
        if ((event.which === 46) && (text.indexOf('.') === -1)) {
            setTimeout(function() {
                if ($this.val().substring($this.val().indexOf('.')).length > 3) {
                    $this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
                }
            }, 1);
        }

        if ((text.indexOf('.') !== -1) &&
            (text.substring(text.indexOf('.')).length > 2) &&
            (event.which !== 0 && event.which !== 8) &&
            ($(this)[0].selectionStart >= text.length - 2)) {
            event.preventDefault();
        }
    });

    $('#someTextInput').bind("paste", function(e) {
        var text = e.originalEvent.clipboardData.getData('Text');
        if ($.isNumeric(text)) {
            if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
                e.preventDefault();
                $(this).val(text.substring(0, text.indexOf('.') + 3));
            }
        }
        else {
            e.preventDefault();
        }
    });

 

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

Really easy registration form with JavaScript validation for Bootstrap

Easy to use registration form with some validation.

This works for me and the site I am using it on, some styling/tweaking may be required for others.

The HTML:

<form action="" method="post" id="fileForm" role="form">
    <fieldset>
      <div class="form-group">
        <label for="email"><span class="req">* </span> Email Address: </label>
        <input class="form-control" required type="text" name="email" id="email" onchange="email_validate(this.value);" />
        <div class="status" id="status"></div>
      </div>

      <div class="form-group">
        <label for="username"><span class="req">* </span> User name:</label>
        <input class="form-control" type="text" name="username" id="txt" minlength="6" onkeyup="Validate(this.value)" placeholder="minimum 6 letters" required autocomplete="off" />
        <div id="errLast"></div>
      </div>

      <div class="form-group">
        <label for="password"><span class="req">* </span> Password: </label>
        <input required name="password" type="password" class="form-control inputpass" minlength="4" maxlength="16" id="pass1" /> </p>

        <label for="password"><span class="req">* </span> Password Confirm: </label>
        <input required name="password" type="password" class="form-control inputpass" minlength="4" maxlength="16" placeholder="Enter again to validate" id="pass2" onkeyup="checkPass(); return false;" />
        <span id="confirmMessage" class="confirmMessage"></span>
      </div>

      <div class="form-group">

        <input type="checkbox" required name="terms" onchange="this.setCustomValidity(validity.valueMissing ? 'Please indicate that you accept the Terms and Conditions' : '');" id="field_terms">   <label for="terms">I agree with the <a href="terms.php" title="You may read our terms and conditions by clicking on this link">terms and conditions</a> for Registration.</label>
        <span class="req">* </span>
      </div>

      <div class="form-group">
        <input class="btn btn-success" type="submit" name="submit_reg" value="Register">
      </div>
    </fieldset>
  </form>
  <!-- ends register form -->

  <script type="text/javascript">
    document.getElementById("field_terms").setCustomValidity("Please indicate that you accept the Terms and Conditions");
  </script>

The JavaScript:

function checkPass()
{
    
    var pass1 = document.getElementById('pass1');
    var pass2 = document.getElementById('pass2');
   
    var message = document.getElementById('confirmMessage');
    
    var goodColor = "#66cc66";
    var badColor = "#ff6666";
    
    if(pass1.value == pass2.value){
        pass2.style.backgroundColor = goodColor;
        message.style.color = goodColor;
        message.innerHTML = "Passwords Match"
    }else{
        pass2.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "Passwords Do Not Match!"
    }
} 
function validatephone(phone) 
{
    var maintainplus = '';
    var numval = phone.value
    if ( numval.charAt(0)=='+' )
    {
        maintainplus = '';
    }
    curphonevar = numval.replace(/[\A-Za-z!"£$%^&,*+_={};:'@#~,.Š/<>?|`¬][]/g,'');
    phone.value = maintainplus + curphonevar;
    maintainplus = '';
    phone.focus;
}

function Validate(txt) {
    txt.value = txt.value.replace(/[^a-zA-Z-'nr.]+/g, '');
}

function email_validate(email)
{
var regMail = /^([_a-zA-Z0-9-]+)(.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+.)+([a-zA-Z]{2,3})$/;

    if(regMail.test(email) === false)
    {
    document.getElementById("status").innerHTML    = "<span class='warning'>Please enter a valid email address.</span>";
    }
    else
    {
    document.getElementById("status").innerHTML	= "<span class='valid'>Email address valid</span>";	
    }
}

function dob_validate(dob)
{
var regDOB = /^(d{1,2})[-/](d{1,2})[-/](d{4})$/;

    if(regDOB.test(dob) === false)
    {
    document.getElementById("statusDOB").innerHTML	= "<span class='warning'>DOB is only used to verify your age.</span>";
    }
    else
    {
    document.getElementById("statusDOB").innerHTML	= "<span class='valid'>Thanks, you have entered a valid DOB!</span>";	
    }
}

function add_validate(address)
{
var regAdd = /^(?=.*d)[a-zA-Zsd/]+$/;
  
    if(regAdd.test(address) === false)
    {
    document.getElementById("statusAdd").innerHTML	= "<span class='warning'>Address is not valid yet.</span>";
    }
    else
    {
    document.getElementById("statusAdd").innerHTML	= "<span class='valid'>Thanks, Address looks valid!</span>";	
    }
}

 

Share this post:
read more