1
\$\begingroup\$

I do need to use jquery autocomplete for two inputs. But I have use same processing script for these two elements.

At this stage I am doing it like this.

 $("#suburb").autocomplete({
 source: function(request, response) {
 $.ajax({
 url: "includes/state_au_ajax.php",
 dataType: "json",
 method: "post",
 data: {
 term : request.term,
 state : $("#state").val()
 },
 success: function( data ) {
 response( $.map( data, function( item ) {
 var code = item.split("|");
 return {
 label: code[0],
 value: code[0],
 data : item
 }
 }));
 }
 });
 },
 autoFocus: true, 
 minLength: 2,
 select: function( event, ui ) {
 var output = ui.item.data.split("|"); 
 $('#zip_code').val(output[1]);
 }, 
 delay: 300
 }); 
 // --- Populate ZIP code according to the value of "Suburb"
 $("#p_suburb").autocomplete({
 source: function(request, response) {
 $.ajax({
 url: "includes/state_au_ajax.php",
 dataType: "json",
 method: "post",
 data: {
 term : request.term,
 state : $("#p_state").val()
 },
 success: function( data ) {
 response( $.map( data, function( item ) {
 var code = item.split("|");
 return {
 label: code[0],
 value: code[0],
 data : item
 }
 }));
 }
 });
 },
 autoFocus: true, 
 minLength: 2,
 select: function( event, ui ) {
 var output = ui.item.data.split("|"); 
 $('#p_zip_code').val(output[1]);
 }, 
 delay: 300
 }); 

My question is, Can I write this without any code duplication?

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Nov 14, 2015 at 14:18
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

You can create separate function like this:

function autoComplete($obj, $valueObj, $zipValue){
 $obj.autocomplete({
 source: function(request, response) {
 $.ajax({
 url: "includes/state_au_ajax.php",
 dataType: "json",
 method: "post",
 data: {
 term : request.term,
 state : $valueObj.val()
 },
 success: function( data ) {
 response( $.map( data, function( item ) {
 var code = item.split("|");
 return {
 label: code[0],
 value: code[0],
 data : item
 }
 }));
 }
 });
 },
 autoFocus: true, 
 minLength: 2,
 select: function( event, ui ) {
 var output = ui.item.data.split("|"); 
 $zipValue.val(output[1]);
 }, 
 delay: 300
 }); 
 }

And then call it appropriately:

 autoComplete($("#suburb"), $("#state"), $('#zip_code'))
 autoComplete($("#p_suburb"), $("#p_state"), $('#p_zip_code'))
answered Nov 14, 2015 at 14:25
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.