Jquery - a way to reuse same code multiple times - javascript

I have some JS functions that looks like :
$('#div1 input[type=radio]').change(function() {
if(this.value=='YES'){
$('#field1').show();
}else{
$('#field1').hide();
}
});
$('#div2 input[type=radio]').change(function() {
if(this.value=='YES'){
$('#field2').show();
}else{
$('#field2').hide();
}
});
$('#div3 input[type=radio]').change(function() {
if(this.value=='YES'){
$('#field3').show();
}else{
$('#field3').hide();
}
});
As they are much similars, there is a way to improve them in less code?
Thanks

The easiest solution is the following. I replaced the if-else hide/show with toggle. I also used === for true type/value comparison.
function changeToggle(inputSelector, fieldSelector, value) {
$(inputSelector).change(function() {
$(fieldSelector).toggle(this.value === value);
});
}
changeToggle('#div1 input[type=radio]', '#field1', 'YES');
changeToggle('#div2 input[type=radio]', '#field2', 'YES');
changeToggle('#div3 input[type=radio]', '#field3', 'YES');
Using a Loop
$("*[id^='div']").each(function(index, div) {
var id = $(div).attr('id').match(/^\w+(\d+)$/)[1];
$(div).find('input[type=radio]').change(function(e) {
$('#field' + id).toggle(this.value === 'YES');
});
});

Try using attribute begins with selector, .closest(), String.prototype.replace() with RegExp /\D/g to match digits in id of closest element where id begins with "div"
$("[id^=div] input[type=radio]").change(function() {
var n = $(this).closest("[id^=div]")[0].id.replace(/\D/g, "");
if (this.value=="YES") {
$("#field" + n).show();
} else {
$("#field" + n).hide();
}
});

Using custom attributes is much better way or if you're in HTML 5 you can use data-attributes. See example below:
<input type="radio" data-show="#field1" />
<input type="text" id="field1" />
<input type="radio" data-show="#field2" />
<input type="text" id="field2" />
<input type="radio" data-show="#field3" />
<input type="text" id="field3" />
JS:
$('input[type=radio]').change(function() {
var targetEl = $(this).data('show');
if($(this).is(':checked')) {
$(targetEl).show();
}else {
$(targetEl).hide();
}
});

Related

JQuery Append To Textbox When Typing

I have 3 textboxes, I want to create something like this: When I type to textbox1, it will duplicate to textbox3, and when I type to textbox2, it will append to textbox3 with a delimiter ( - ).
For example, if I write STACK to textbox1, textbox3 will result STACK, then if I wrote down textbox2 with OVERFLOW, textbox3 value is: STACK-OVERFLOW
Here's my code at fiddle:
$(function() {
$("#text1").keyup(function() {
$('#text3').val(this.value);
});
$("#text2").keyup(function() {
$('#text3').val.append('-'+this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text1" />
<input type="text" id="text2" />
<input type="text" id="text3" />
Anyone can fix my code?
$(function() {
var text1value , text2value;
$("#text1").keyup(function() {
text1value = $(this).val();
$('#text3').val(text1value);
});
$("#text2").keyup(function() {
text2value = $(this).val();
$('#text3').val(text1value+'-'+text2value);
});
});
You need to check also if text2 is empty so you don't have to concatenate the '-' in that case.
JS Fiddle
$(function() {
$("#text1").keyup(function() {
var text2 = $('#text2').val();
var temp = $(this).val();
if (text2 != '') {
temp = $(this).val()+'-'+text2;
}
$('#text3').val(temp);
});
$("#text2").keyup(function() {
var temp = $('#text1').val()+'-'+$(this).val();
$('#text3').val(temp);
});
});
$(function() {
$("#text1").keyup(function() {
$('#text3').val(this.value);
});
$("#text2").keyup(function(e) {
$('#text3').val(function(index, val) {
return $("#text1").val() + "-" + e.target.value;
});
});
});
This should do it
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text1" />
<input type="text" id="text2" />
<input type="text" id="text3" />
This is one way to do it:
http://jsfiddle.net/6qojd9L4/
$(function() {
$("#text1").keyup(function() {
$('#text3').val(this.value + '-' + $('#text2').val());
});
$("#text2").keyup(function() {
$('#text3').val($('#text1').val() + '-'+this.value);
});
});

Use same function on multiple elements

I need this function to work on multiple elements in the form, right now it only works on TfDiagnosis.
How do I use it on TfDiagnosis and TfDiagnosis2 with results in TfSnowmed and TfSnowmed2?
JQUERY
$(function snowmedlist() {
$('#TfDiagnosis').on('click keyup change blur', function() {
if ($('#TfDiagnosis').val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($('#TfDiagnosis').val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
});
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2"></td>
It's easy to work on groups of elements using class names.
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="diagnosis" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed">
js:
$('.diagnosis').on('click keyup change blur', function() {
if($(this).val() == "...") {
$(this).next().val(1.00);
}
})
This way .next() is always the next element, so you don't need to keep passing IDs around. You can then store the data outside of the function to get rid of a cluster of IF statements:
var myData = []
myData['[D]Anterograde amnesia (780.93)'] = '206789002';
myData['[D]Chills with fever (780.60)'] = '206760004';
...then substitute the look-up from the array....
$('.diagnosis').on('click keyup change blur', function() {
$(this).next().val(myData[$(this).attr(id)]);
})
You can use
$('#TfDiagnosis, #TfDiagnosis2').on('click keyup change blur', function() {
if($(this).attr('id') == 'TfDiagnosis' ){
if ($(this).val() == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
if ($(this).val() == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
}else{
//Stuff to do in case it is the #TfDiagnosis2
}
});
The most efficient way to make your function work on multiple inputs is to use event delegation:
$(document).on('click keyup change blur', 'input', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});
Which will call the function for any input on the page. You probably want to assign a class to the specific inputs you want to use like so:
HTML
<input name="TfDiagnosis" type="text" id="TfDiagnosis" class="TfInput" size="100">
<input type="text" name="TfSnowmed" id="TfSnowmed" class="TfInput">
<input name="TfDiagnosis2" type="text" id="TfDiagnosis2" class="TfInput" size="100" >
<input type="text" name="TfSnowmed2" id="TfSnowmed2" class="TfInput">
JavaScript
$(document).on('click keyup change blur', '.TfInput', function() {
var value = $(this).val(); //Get the value only once
if (value == '[D]Anterograde amnesia (780.93)') {
$('#TfSnowmed').val(206789002);
}
else if (value == '[D]Chills with fever (780.60)') {
$('#TfSnowmed').val(206760004);
}
});

How to make localstorage of focus in textbox using Jquery dynamic?

<input id="input1" type="text" />
<br />
<input id="input2" type="text" />
I have followed this simple script that stores the focus on the input text.
$(document).ready(function() {
changeFocus();
$("#input1").click(function(){
localStorage.setItem('txtObjectid', "input1");
changeFocus();
return false;
});
$("#input2").click(function(){
localStorage.setItem('txtObjectid', "input2");
changeFocus();
return false;
});
});
function changeFocus(){
if(localStorage.getItem('txtObjectid')==null)
id="input1"
else
id=localStorage.getItem('txtObjectid');
var v = "#" + id;
$(v).focus();
}
What I want to learn/know about is how to make the script flexible? How could I make this so that it won't search of the id = "input1" instead it will search for input[type=text]?
Something like this should do it
$(document).ready(function () {
var id = 'input1';
if (localStorage.getItem('txtObjectid')) {
id = localStorage.getItem('txtObjectid');
}
$('#' + id).focus();
$('input[type="text"]').on('focus', function () {
localStorage.setItem('txtObjectid', this.id);
});
});
FIDDLE

using one one event for multiple purpose

I have buttons like this :
<input class="btnRating" type="button" value="Project Rate" />
<input class="btnRating" type="button" value=" Education Rate" />
<input class="btnRating" type="button" value="Achievement Rate" />
i want to use 3 buttons as per different click ,different purpose
and in one event i want to write like this :
// Event For Open Modal Pop for rating
$('.btnRating').on("click", function (ele) {
if(thisbutton ==Project )
{
// do something for project related
}
if(thisbutton ==Education)
{
// do something for Education related
}
if(thisbutton ==Achievement)
{
// do something for project related
}
});
how do i write event like this?
If clicking each button has completely different consequences
It's more logical if they are handled by different events. Different meaning they don't share most of their code. Even if you don't want to write three events (why? it's the same amount of lines of codes), it fits better the use case.
If clicking each button has similar consequences
This seems to be your case, since all buttons have "Rate" in their name. If so, you are right that you should only have one event, since most of the code will be the same. However, instead of using different code paths (if/else or switches), it's better if you add a data- attribute to your buttons to so that, by using the value in those attributes, the same code can behave in different ways. Let's say the only difference between them is a "Rate Multiplier". You could do this:
<input type="text" id="costToMultiplyByRate" />
<input class="btnRating" type="button" value="Project Rate" data-rate="5" />
<input class="btnRating" type="button" value=" Education Rate" data-rate="4" />
<input class="btnRating" type="button" value="Achievement Rate" data-rate="10" />
$('.btnRating').on("click", function (ele) {
var rate = ele.getAttribute("data-rate");
var cost = document.getElementById("costToMultiplyByRate");
alert(rate * cost);
}
However, if by adding only one or two data attributes you can't make the three buttons use exactly the same code, I suggest you use multiple events.
Try
$('.btnRating').on("click", function (ele) {
if (this.value.indexOf('Project') > -1) {
// do something for project related
} else if (this.value.indexOf('Education') > -1) {
// do something for Education related
} else if (this.value.indexOf('Achievement') > -1) {
// do something for project related
}
});
You can test the value of the cbutton
$('.btnRating').on("click", function (ele) {
if (this.value == 'Project Rate') {
// do something for project related
} else if (this.value == ' Education Rate') {
// do something for Education related
} else if (this.value == 'Achievement Rate') {
// do something for project related
}
});
Better solution is to have a unique selector for the buttons and write separate handlers for each one
Try:
$('.btnRating').on("click", function (ele) {
var val = $(this).val();
if(val == "Project Rate"){
}
else if(val == " Education Rate"){
}
else if(val == "Achievement Rate"){
}
});
I recommend add classes to buttons
<input class="btnRating project" type="button" value="Project Rate" />
<input class="btnRating education" type="button" value=" Education Rate" />
<input class="btnRating Achievement" type="button" value="Achievement Rate" />
And then use separated events
$('.btnRating.project').on("click", function (ele) {
// do something for project related
});
add attribute : data-event
<input class="btnRating" type="button" value="Project Rate" data-event="project" />
then u can use a switch
$('.btnRating').on("click", function (ele) {
switch($(this).data("event")) {
case "project" :
//fire your function
break;
}
}
Can you please try this,
In HTML section:
<input class="btnRating" id="ProjectRate" type="button" value="Project Rate" />
<input class="btnRating" id="EducationRate" type="button" value=" Education Rate" />
<input class="btnRating" id="AchievementRate" type="button" value="Achievement Rate" />
In Script:
<script>
$(function(){
// Event For Open Modal Pop for rating
$('.btnRating').click(function (ele) {
var thisbutton = $(this).attr('id');
if(thisbutton =="ProjectRate")
{
// do something for project related
}else if(thisbutton =="EducationRate")
{
// do something for Education related
}else if(thisbutton =="AchievementRate")
{
// do something for project related
}else{
// do your default
}
});
});
</script>
<input class="btnRating" type="button" data-action="project" value="Project Rate" />
<input class="btnRating" type="button" data-action="education" value=" Education Rate" />
<input class="btnRating" type="button" data-action="achievement" value="Achievement Rate" />
$(".btnRating").click(function () {
var action = $(this).attr("data-action");
if (action === "project") {
// do project
} else if (action === "education") {
// do education
}
});
This way you can have any value (text) on the button, which is good if you want to globalize your website in the future.
$('.btnRating').click(function (ele) {
if($(this).val()=="Project Rate" )
{
// do something for project related
}
else if($(this).val() =="Education Rate")
{
// do something for Education related
}
else if($(this).val() =="Achievement Rate")
{
// do something for project related
}
});
Demo here http://jsfiddle.net/3Mf3j/
Try this:
$('.btnRating').on("click", function (ele) {
var value = $(this).val();
if(value.indexOf("Project Rate") != -1)
{
// do something
}
else if(value.indexOf("Education Rate") != -1)
{
// do something
}
else if(value.indexOf("Achievement Rate") != -1)
{
// do something
}
});
Use event.delegate http://api.jquery.com/delegate/ - something like http://jsfiddle.net/aamir/zw27q/2/
I will recommend that use unique css classes for each buttons as if you change the Value of each input than you have to change your JS as well. So instead of checking for val=='Project Rate you should check for $this.hasClass('rateProj')
$(".btns").delegate("input", "click", function () {
var $this = $(this),
val = $this.val();
if (val =='Project Rate') {
//code
}
//more if statements
});
I suggest you use data-attribute to achieve this. as comparing string can cause more time for checking...
I have created jsfiddle for this.
http://jsfiddle.net/x4yyp/2/
$(document).on("click", ".btnRating", function () {
var optionValue = $(this).data("optionvalue");
if(optionValue == 1)
{
alert("hello");
}
else if(optionValue == 2)
{
alert("your name");
}
else if(optionValue == 3)
{
alert("your email");
}
});
this will help you
$(document).ready(function(e) {
$('.btnRating').on("click", function (ele) {
var btnType = $(this).val();
switch(btnType) {
case 'Project Rate':
// your action;
break;
case ' Education Rate':
// your action;
break;
case 'Achievement Rate':
// your action;
break;
}
});
});

Jquery - check the value of inputs texts

I have some input texts like this :
<input type="text" value="5" maxlength="12" id="qty" class="input-text qty" name="qty2050" tabindex="1">
and
<input type="text" value="0" maxlength="12" id="qty" class="input-text qty" name="qty2042" tabindex="1">
And I want to check with jquery the values of each input, to execute a function if there is a quantity different from 0 in one input.
EDIT
How can I do that on page before unlod?
Thanks for help.
try in this way-
$(window).unload(function() {
$('.input-text qty').each(function (){
var val = parseInt($(this).val(),10);
// you can use math.floor if your input value is float-
//var val = Math.floor($(this).val());
if(val !== 0)
alert(val);
});
});
$('.input-text').change( function() {
if($(this.val() != "0")){ //
action here
}
});
You shouldn't have two same IDs on a page.
Quite simple should be:
$('input.input-text.qty').each(function(){
if ($(this).val() !== '0') {
alert('Gotcha!');
return false; //quit loop since we're ok with 1 occurance
}
});
Use change(): http://api.jquery.com/change/
Example: To add a validity test to all text input elements:
$("input[type='text']").change( function() {
// check input ($(this).val()) for validity here
});
var checkInput = function() {
if(this.value !== '0') {
// do something
}
}
$(window).bind('unload', checkInput);
$('input[type=text]').change(checkInput);
I hope this helps.
If you really want this on the unload event then something like this will work (its untested), otherwise bind to whatever event you want:
$(window).unload( function() {
$('.input-text qty').each(function (){
if( $(this).val() !== '0' ) {
alert("there is a 0");
return false;//breaks out of the each loop, if this line present will only get one alert even if both fields contain 0
}
});
});

Categories

Resources