I have 2 input text and button.. I want to make exchange value between 2 inputs at the same time. here is my code.
$("button").on('click', function() {
if (!($(this).hasClass("clicked"))) {
$(this).addClass("clicked");
$(".first").val($(".second").val());
$(".second").val($(".first").val());
} else {
$(this).removeClass("clicked");
$(".first").val($(".second").val());
$(".second").val($(".first").val());
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input class="first" type="text" value>
<input class="second" type="text" value>
<button type="button">Exchange</button>
</div>
the first input works fine but the second not working.. I want the exchange happen at the same time.
You are overwriting one of the two before reading that other value. So you end up with twice the same value.
The traditional way is to use a temporary variable:
$("button").on('click', function() {
$(this).toggleClass("clicked");
var temp = $(".first").val();
$(".first").val($(".second").val());
$(".second").val(temp);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input class="first" type="text" value>
<input class="second" type="text" value>
<button type="button">Exchange</button>
</div>
At the same time note how you can shorten your code with the toggleClass method.
Alternative
Just to provide an alternative, you can do this without an explicit extra variable, using the ES6 destructuring assignment. For that to work, you need to have an assignable property for the input value. Of course, the DOM value property would just be that:
$("button").on('click', function() {
$(this).toggleClass("clicked");
[$(".first").get(0).value, $(".second").get(0).value] =
[$(".second").val(), $(".first").val()];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input class="first" type="text" value>
<input class="second" type="text" value>
<button type="button">Exchange</button>
</div>
$("button").on('click', function() {
var firstVal = $(".first").val()
var secondVal = $(".second").val()
if (!($(this).hasClass("clicked"))) {
$(this).addClass("clicked");
$(".first").val(secondVal);
$(".second").val(firstVal);
} else {
$(this).removeClass("clicked");
$(".first").val(secondVal);
$(".second").val(firstVal);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input class="first" type="text" value>
<input class="second" type="text" value>
<button type="button">Exchange</button>
</div>
You need to store the original values first, when you try to swap them without storing you forget that one of the values is overridden.
that because the value was changed . try to save old value on var
$("button").on('click', function() {
var first = $(".first").val(),
second = $(".second").val();
if (!($(this).hasClass("clicked"))) {
$(this).addClass("clicked");
$(".first").val(second);
$(".second").val(first);
} else {
$(this).removeClass("clicked");
$(".first").val(second);
$(".second").val(first);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input class="first" type="text" value>
<input class="second" type="text" value>
<button type="button">Exchange</button>
</div>
Use an intermediate temp variable to swap them.
$("button").on('click', function() {
if (!($(this).hasClass("clicked"))) {
$(this).addClass("clicked");
var temp = $(".first").val();
$(".first").val($(".second").val());
$(".second").val(temp);
} else {
$(this).removeClass("clicked");
var temp = $(".first").val();
$(".first").val($(".second").val());
$(".second").val(temp);
}
});
Working DEMO
Related
I have the following code
<input id="in" value="50px"/>
<div id="out">this is my output</div>
how to bind using the jquery the #in value to the #out's font-size?
Constraints:
a) the variant from this codepen should also work:
$(function() {
$("#out").css("fontSize", $("#in").val());
$("#in").on("input", function(e) {
$("#out").css("fontSize", $("#in").val());
});
$("#in").val("5px"); // should update the font size!
});
b) when the browser is autofill-ing the values into the boxes, the value should change...
You have to apply your CSS with the .css function from JQuery when the event gets fired (here keyup).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="in" value="18px"/>
<div id="out">this is my output</div>
<script>
$('#in').on('keyup', function () {
$('#out').css({'font-size':$(this).val()});
});
</script>
Use .css function of jquery
$('#in').keyup(function() {
$("#out").css('font-size', $('#in').val()+"px")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="in" value="18" />
<br><br>
<br>
<div id="out">this is my output</div>
With pure javascript:
const inp = document.querySelector("#inp");
const out = document.querySelector("#out");
inp.addEventListener("keyup", function(){
out.style.fontSize = inp.value + "px";
})
<input id="inp" type="text" placeholder="write a value">
<div id="out">this is my output</div>
Check this fiddle:
You will need to validate the information before change the font size:
<input id="in" value="18px"/>
<div id="out">this is my output</div>
$(function() {
$("#in").on('input',function(e){
$("#out").css("fontSize", $("#in").val());
});
});
https://jsfiddle.net/3vhdfruq/1/
var inp = document.querySelector("#inp");
var out = document.querySelector("#out");
inp.addEventListener("keyup", function(){
out.style.fontSize = inp.value + "px";
})
<input id="inp" type="text" value="20">
<div id="out">this is my output</div>
Here I need to get all the values entered in the input field. But it echoes only the first value.
ie. When I press the + and give some values, I need to get that value too.
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('#package').change(function() {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
alert(arr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add"></div>
</div>
$('.package').change(function() {
You are using an ID in your input type="text". IDs are only used once. If you want to add the listener to all of your textfields use classes.
In addition to that the .change(function() is only once called, when the dom is ready. That will be a problem too. So the change listener is not added to the generated textfields. Maybe you use something like...
$('.package').on('change', 'input', function() {
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="add1">
<h6>Sales Package </h6>
<div>
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<input type="submit" value="+" class="add">
</div>
</div>
<script type="text/javascript">
var addInput = function(e) {
var arr = [];
$("input.packageclass").each(function() {
arr.push($(this).val());
});
alert(arr);
};
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input class="packageclass" type="text" name="selprice" /><input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
$(this).closest('.add1').after(clone);
$('.packageclass').unbind().bind('change', addInput);
});
$(document).on("click", ".remove", function() {
$(this).parent(".add1").remove();
});
});
$('.packageclass').unbind().bind('change', addInput);
</script>
Just using loop you can get the particular value from loop.
for (var i = arr.length - 1; i >= 0; i--) {
arr[i];
//work with arr[]
}
I have used event delegation to capture the events and take appropriate action.
In this, you can add a event listener to your parent element i.e., click to the .body in my case. When I click on the .add button, the event propagates and .body click handler gets invoked. By checking for event.target we can find out the origin of event and add or remove the divs.
Similary we can listen for the change event of the input boxes and take appropriate actions.
$('#body').click(function(e) {
if(e.target.className === 'add') {
$('#body').append(`
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
<button class="remove">-</button>
</div>
`);
}
if(e.target.className === 'remove') {
$(e.target).parent().empty();
}
});
$('#body').change(function(e) {
console.log(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="body">
<h6>Sales Package </h6>
<div class="add1">
<input type="text" name="package" placeholder="Ex:34" id="package" class="packageclass">
<button class="add">+</button>
</div>
</div>
Just add class="packageclass" to the input when creating your clone variable.
https://jsfiddle.net/289xvmu7/
var clone = '<div class="add1"><input type="text" name="selprice" class="packageclass"/> <input type = "submit" value = "+" class = "add" ><input type = "submit" value = "-" class = "remove" ></div>';
I have a div that has multiple input fields. My HTML looks like this:
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" onclick="getAllValues();" />
After I click the image, it must get all the values inside the mainDiv. How can I do this?
$("#getallvalues").click(function() {
var values = $("#mainDiv input").map(function() {
return $(this).val()
}).get().join(",");
console.log(values)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" id="getallvalues" />
Loop through each input then get the value and use .map()
var price = 0;
var tax = 0;
var others = 0;
$("#getallvalues").click(function() {
$("#mainDiv input").each(function() {
if ($(this).attr("id") == "price") {
price = $(this).val()
}
if ($(this).attr("id") == "tax") {
tax = $(this).val()
}
if ($(this).attr("id") == "others") {
others = $(this).val()
}
})
console.log("price " + price)
console.log("tax " + tax)
console.log("others " + others)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<input type="text" id="price" /> <br/>
<input type="text" id="tax" />
<input type="text" id="others" />
</div>
<img src="img/img.gif" id="getallvalues" />
You can use .map() to iterate over element and return the value in call back along with .get() to get them in array:
function getAllValues(){
$('#mainDiv input').map({
return this.value;
}).get(); // Output: ["priceval","taxval","otherval"]
}
You can use above array to create the data in whichever format(csv,json,etc) you want for further processing.
Loop through all the inputs in mainDiv
$('#mainDiv input').each(function(){
// Do what ever
})
Another way of doing this is like follows:
$('#mainDiv').find('input').each(function (index, element) {
var yourValue = element.value; // or $(element).val();
// And rest of your code
});
$('#mainDiv input').each(function(){
console.log(this.val());
})
I tried to make a warning if the input is not the same , like the example below:
$data = document.getElementById("target").value = "";
$("#target").keyup(function() {
if ($data.length > 3) {
$("#target").css("border-color", "red");
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="target" class="form-control" type="text" value="">
</form>
But it did not work, so if true then the border-color has to change
You need to move your $data variable into inside keyup events. Since you've add jQuery tag, I've selecting object using jQuery method too.
UPDATE
Simplify the code
$("#target").keyup(function(){
var $data = $("#target").val();
$("#target" ).css("border-color", $data.length > 3 ? "red" : "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="target" class="form-control" type="text" value="">
</form>
In provided example, $data holds ""(empty string)
In event-handler-function, this refers to the element on which event is invoked hence this.value will return the value of the element.
var $data = $("#target");
$data.val('');
$data.keyup(function() {
if (this.value.length > 3) {
$("#target").css("border-color", "red");
} else {
$("#target").css("border-color", "");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="target" class="form-control" type="text" value="">
</form>
Another approach I would like to suggest is to using jQuery.toggleClass instead of jQuery.css
var $data = $("#target");
$data.keyup(function() {
$("#target").toggleClass('error', this.value.length > 3);
});
.error {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="target" class="form-control" type="text" value="">
</form>
I am attempting to toggle disabled = true|false on a <input type="text">, using a checkbox. I am able to get the value of the input, but I cannot set the input to disabled.
my jquery/js code
<script>
$(function () {
$('.date').datepicker();
$('body').on('change', '.housing', function () {
if ($(this).val() == 'dorms') {
$(this).parent().next(".dorms").show();
} else {
$(this).parent().siblings(".dorms").hide();
}
});
$('body').on('change', '.single', function () {
if ($(this).checked) {
$('#echo1').text($(this).prev(".roommate").val()); // this works
$(this).prev(".roommate").val(''); // does not empty the input
$(this).prev(".roommate").disabled = true; // does not set to disabled
$(this).prev(".roommate").prop('disabled', true); // does not set to disabled
$('#echo2').text($(this).prev(".roommate").prop('disabled')); // always says false
} else {
$('#echo1').text($(this).prev(".roommate").val()); // this works
$(this).prev(".roommate").disabled = false; // always stays false
$('#echo2').text($(this).prev(".roommate").prop('disabled')); // always says false
}
});
});
</script>
my html code
<div class="registration_housing particpant_0" data-sync="0">
<div>
<label class="particpant_0"></label>
</div>
<div>
<label>Off Campus (not included)</label>
<input type="radio" name="housing[0]" value="none" class="housing" />
</div>
<div>
<label>On Campus</label>
<input type="radio" name="housing[0]" value="dorms" class="housing" />
</div>
<div class="dorms" style="display:none;">
<div>
<label>Checkin:</label>
<input type="text" name="check_in[0]" class="date" />
</div>
<div>
<label>Checkout:</label>
<input type="text" name="check_out[0]" class="date" />
</div>
<div>
<label>Roommate:</label>
<input type="text" name="roommate[0]" class="roommate" />
<input type="checkbox" name="roommate_single[0]" value="single" class="single" />check for singe-occupancy</div>
</div>
<div class="line">
<hr size="1" />
</div>
</div>
<div>
<label id="echo1"></label>
</div>
<div>
<label id="echo2"></label>
</div>
you can see this at http://jsfiddle.net/78dQE/1/
Any idea why I can get the value of (".roommate") - ie. $(this).prev(".roommate").val()
but
$(this).prev(".roommate").disabled = true;
OR
$(this).prev(".roommate").prop('disabled', true);
will not set (".roommate") to disabled?
Your issue is mixing jquery with DOM element attributes
change if ($(this).checked) { to if (this.checked) {
With jquery you would do
$(this).is(':checked') // But you could just do this.checked
And
$(this).prev(".roommate").prop('disabled', false); // or $(this).prev(".roommate")[0].disabled = false;
instead of
$(this).prev(".roommate").disabled = false;
Fiddle
So you just probably need this:
$('body').on('change', '.single', function () {
$(this).prev(".roommate").prop('disabled', this.checked).val('');
});