Leon
Leon

Reputation: 33

Combining two jQuery function into one

I want to combine my two jQuery functions into one. But I don't know how. What do I need to change to combine these two into one function?

Here is the Code:

$('#keyword').on('keyup', function (e) {
    console.log(e.keyCode);
    console.log($(this).text());
    $('input[name="q"]').val($(this).val());
    $('g-search').html($(this).val());
});

$(function () {
    $('#title').on('keyup', function (e) {
        console.log(e.keyCode);
        console.log($(this).val());
        var title = $(this).val();
        $('span.title').text(title);
        $('g-search').html(title);
    });
});

Upvotes: 0

Views: 93

Answers (4)

madalinivascu
madalinivascu

Reputation: 32354

Add a common class to each element

html:

<input class="key common-class" type="text" size="50" maxlength="63" id="keyword"/>

<input class="url1 common-class"  type="text" data-limit="60" size="50" maxlength="74" id="url"/>

js:

$('.common-class').on('keyup', function (e) {
      //combined code 
      var val = $(this).val();
   if($(e.target).is('#keyword')) {
     $('input[name="q"]').val(val);
   } else {
    $('span.title').text(val);
   }
   $('g-search').html(val);
});

Upvotes: 2

nisar
nisar

Reputation: 1065

possible check this fiddle jsfiddle

$('#keyword,#title').on('keyup', function (e) {

        console.log(e.keyCode);

        console.log($(this).text());

        $('input[name="q"]').val($(this).val());

        $('g-search').html($(this).val());

    });

Upvotes: 2

Jaber
Jaber

Reputation: 277

You can write your logic in a single function by like this in case of different types of events.

$(function () {
    $('#keyword').on('keyup', function (e) {
        anotherFunction(this);
    });
    $('#title').on('keyup', function (e) {
            anotherFunction(this);
    });
});

function anotherFunction(val){

}

Or you can do like this.

$('#keyword,#title').on('keyup', function (e) {


});

Upvotes: 4

Bharat
Bharat

Reputation: 2464

You just need to add your both Ids on same event function like below code.

$('#keyword,#title').on('keyup', function (e) {
  //Your code
})

Upvotes: 1

Related Questions