Reputation: 328
I currently have the following code to update a URL. How do I combine this into something more robust so that I'm not repeating myself 3 times basically. I only want this to update when one of the fields is changed.
$(document).ready(function(){
$('#device_select').change(function() {
var device = $(this).val();
var face = $('#face_select').val();
var position = $('#position_select').val();
document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position;
});
$('#face_select').change(function() {
var device = $('#device_select').val();
var face = $(this).val();
var position = $('#position_select').val();
document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position;
});
$('#position_select').change(function() {
var device = $('#device_select').val();
var face = $('#face_select').val();
var position = $(this).val();
document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position;
});
});
Upvotes: 3
Views: 1070
Reputation: 1914
What about this approach ?
$(document).ready(function(){
['#position_select', '#device_select', '#face_select'].forEach(
function(ev){
$(ev).change(function() {
var device = $('#device_select').val();
var face = $('#face_select').val();
var position = $('#position_select').val();
document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position;
});
}
)
}
)
Upvotes: 1
Reputation: 310
Why not encapsulate your code in a function?
function updateURL() {
var device = $('#device_select').val();
var face = $('#face_select').val();
var position = $('#position_select').val();
document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position;
}
You can then call the function anytime you want :
$(document).ready(function(){
$('#device_select').change(updateURL);
$('#face_select').change(updateURL);
$('#position_select').change(updateURL);
});
Even better, you could add a second function so your code is more readable :
function listenForChanges(){
$('#device_select').change(updateURL);
$('#face_select').change(updateURL);
$('#position_select').change(updateURL);
}
And call this function on document.ready
:
$(document).ready(listenForChanges);
Upvotes: 3
Reputation: 766
$('#position_select, #device_select, #face_select').change(function() {
var device = $('#device_select').val();
var face = $('#face_select').val();
var position = $('#position_select').val();
document.getElementById("add_dev_rack").href="127.0.0.1:8080/dcim/devices/"+device+"/edit/?face="+face+"&position="+position;
});
Have you tried somethign like this?
Upvotes: 5