javascript - How to create a function containing custom var -
i have written following function sync input fields:
$(".dp1").on('change', function(e){ var datevalue = $($(this)[0]).val(); $.each($('.dp1'), function(index, item){ $(item).val(datevalue); }); }); $(".dp2").on('change', function(e){ var datevalue = $($(this)[0]).val(); $.each($('.dp2'), function(index, item){ $(item).val(datevalue); }); }); $(".rooms").on('keyup', function(e){ var datevalue = $($(this)[0]).val(); $.each($('.rooms'), function(index, item){ $(item).val(datevalue); }); }); $(".persons").on('keyup', function(e){ var datevalue = $($(this)[0]).val(); $.each($('.persons'), function(index, item){ $(item).val(datevalue); }); });
as function exact same 1 every time, guess there better way combine one. thinking of like
my_custom_function(my_custom_value){ var datevalue = $($(this)[0]).val(); $.each($('my_custom_value'), function(index, item){ $(item).val(datevalue); }); } my_custom_function('.dp1, .dp2, .rooms, .persons');
i know there way not know how achieve this. thankful if able me out!
you can write common function , call function approprite parameters.
function my_custom_function(selector, event) { $(selector).on(event, function (e) { var datevalue = this.value; $.each($(selector), function (index, item) { $(item).val(datevalue); console.log(item); }); }); } my_custom_function(".dp1", "change") my_custom_function(".dp2", "change") my_custom_function(".rooms", "keyup") my_custom_function(".persons", "keyup")
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="dp1"></input> <input type="text" class="dp1"></input> <br/> <input type="text" class="dp2"></input> <input type="text" class="dp2"></input> <br/> <input type="text" class="rooms"></input> <input type="text" class="rooms"></input> <br/> <input type="text" class="persons"></input> <input type="text" class="persons"></input>
Comments
Post a Comment