Damian Smith
Damian Smith

Reputation: 95

cleaning up multiple jquery functions

I have 12 functions all doing the same job but simply targeting different elements. I am trying to clean up my code and see if there is way to create one single function for it.

example:

    function incrementValue()
{
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
}
function incrementValue2()
{
    var value = parseInt(document.getElementById('number2').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number2').value = value;
}

Basically each time the button is clicked it increments the value inside the input.

HTML:

<input type="button" onclick="incrementValue()" value="VOTE" />
<a href="option1.html" title="More information"><img src="icon.png" /></a>

I have tried but always seems to be something breaking :/ Not sure what I am doing wrong. Can't seem to find clear tutorials on this, so if someone could maybe just point me towards a tutorial I can then work out the code and answer this myself!

Thanks

Upvotes: 0

Views: 71

Answers (2)

Sirko
Sirko

Reputation: 74036

It looks like you just need a parametrized function:

function incrementValue( target )
{
    var el = document.getElementById( target );
    var value = parseInt( el.value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    el.value = value;
}

Then you can call this function with

incrementValue( 'number' );
incrementValue( 'number2' );
// etc.

Upvotes: 3

Siva Charan
Siva Charan

Reputation: 18064

Use Attribute Starts With Selector to handle this case

$("input[id^=number]")

Upvotes: 0

Related Questions