1

I have a text input that is disabled using the disabled attribute, but I add input to it on the click of a certain classes.

On the click of class I (.I), I add a letter I to the existing text, if any, inside the input.

On the click of class O (.O), I add a letter O to the existing text, if any, inside the input.

However nothing seems to be happening when I click the classes.

Here is my code:

    $('.I').click(function(){
        $('#code').text($('#code').text()+"I");
    });
    $('.O').click(function(){
        $('#code').text($('#code').text()+"O");
    });

Here is a JSFiddel replicating the problem: http://jsfiddle.net/q3xBY/

IrfanM
  • 715
  • 3
  • 10
  • 21

3 Answers3

2

To get and set the value of an input element, you should use .val() instead of .text().

$('.I').click(function(){
    $('#code').val($('#code').val()+"I");
});
$('.O').click(function(){
    $('#code').val($('#code').val()+"O");
});
John S
  • 21,212
  • 8
  • 46
  • 56
0

Instead of hardcoded each click like that, you can give same class for all your button:

<button class="I button">I</button>
<button class="O button">O</button> 

Then you can apply jQuery to achieve like what you describe:

$('.button').click(function(event) {
    var text = $(this).text();
    $('input:text').val(function(index, val) {
        return val + text;
    });
});

Updated Demo

Eli
  • 14,779
  • 5
  • 59
  • 77
0

As John S said - you're going to want to use .val() and not .text(). In case you have multiple instances of this on one page and you don't want to repeat yourself I've provided a solution.

#foo is the text input you'd like to change when you click on the text input modifiers. The ul[data-change] can be the container for the modifiers and has a data-change attribute to specify which input element on the page the modifiers will target. Each of the a modifier elements have a data-value attribute that specifies what will be added to the targeted input on mouseclick.

HTML:

<input type="text" id="foo" value="" disabled="disabled" />
<ul data-change="#foo">
    <li><button id="i" data-value="i">i</button></li>
    <li><button id="a" data-value="a">a</button></li>
</ul>

JS:

$('[data-change] button').on('click', function(){
    var target = $(this).closest('[data-change]').data('change');
   $(target).val( $(target).val() + $(this).data('value') );
});

Here's a fiddle: http://jsfiddle.net/vpC6D/1/

kyle.stearns
  • 2,326
  • 21
  • 30