UserIsCorrupt
UserIsCorrupt

Reputation: 5025

If input box contains certain number of characters

<input type="text"/> <button>Go</button>

<div id="example">
</div>

How can I .append "Blah" in #example if input contains 5 characters when button is clicked, and .append "Other" if it doesn't?

Upvotes: 2

Views: 1716

Answers (6)

Eric
Eric

Reputation: 6345

If you didn't want to use jquery you could do...

HTML

<input id="input1" type="text"/> <button onclick="go('input1')">Go</button>

<div id="example">
</div>

JavaScript

function go(inputId){
    document.getElementById("example").innerHTML += document.getElementById(inputId).value.length === 5 ? "bla" : "other";
}

This involved changing the HTML to include an id for the input and an onclick event handler for the button.

Upvotes: 0

gion_13
gion_13

Reputation: 41533

$('button').on('click',function() { 
    $('#example').text(
        $('#example').text() +
        ($('input[type=text]').val().length==5?'Blah':'Other')
    );
} );

Upvotes: 0

Loktar
Loktar

Reputation: 35309

Pure JS way

var butt = document.getElementsByTagName("button")[0],
    input =  document.getElementsByTagName("input")[0],
    example = document.getElementById("example");

butt.onclick = function(){
    if(input.value.length == 5){
        example.textContent += "blah";
    }else{
        example.textContent += "other";
    }
}

Live Demo

Upvotes: 0

Joseph
Joseph

Reputation: 119827

var example = $('#example');    //get example div
var input = $('input').get(0);  //get first input in the set of inputs

$('button').click(function(){   //bind click handlers to (any) button
   var value = input.value;     //get the (first) input's value
   if(value.length === 5){      //check the value
      example.append('Blah');
   } else {
      example.append('Other');
   }
});

Upvotes: 1

Ohgodwhy
Ohgodwhy

Reputation: 50767

$(function(){
  $('button').click(function(){        
    if($('input').val().length == 5){
      $('#example').append('blah');
    }else{
      $('#example').append('Other');
    }
  }); 
}); 

Upvotes: 1

zerkms
zerkms

Reputation: 254886

$('button').click(function() {
    var $example = $('#example');
    if ($('input').val().length == 5) {
        $example.append('Blah');
    } else {
        $example.append('Other');
    }
});

http://jsfiddle.net/zerkms/cks45/

Upvotes: 1

Related Questions