I have a button each time it is clicked, a new select input will be added. But I want the id and name of the select changed as well.My codes was:
<section>
<div class="container">
<select id="myId_1" name="myName_1">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</section>
<button type="button" id="myBtn">add</button>
$(document).ready(function () {
$('#myBtn').click(function(){
var addEvent = $('.container').html();
var addEventCell = $('<div class="container">'+addEvent+'</div>');
$('section').append(addEventCell);
});
});
But my code just duplicates the id and name of select. I want it to change to myId_2, myName_2,myId_3,myName_3 and so on.
I am new to javascript. It could be easy to you guys. Thanks for help !
this is the link for JSFiddle working here. It may be useful for you
$(document).ready(function () {
$('#myBtn').click(function(){
var addEvent = $('.container').html();
var selectid = $('section :last-child select').attr('id');
var selectname = $('section :last-child select').attr('name');
var tempId = parseInt(selectid.split('_')[1])+1;
var tempName = parseInt(selectname.split('_')[1])+1;
var addEventCell = $('<div class="container">'+addEvent+'</div>');
var newId = selectid.split('_')[0]+"_"+tempId;
var newName = selectname.split('_')[0]+"_"+tempName ;
var select = $('select', addEventCell);
select.attr('id', newId).attr('name', newName);
$('section').append(addEventCell);
});
});
$(document).ready(function () {
$('#myBtn').click(function(){
var addEvent = $('.container:last').html();
var addEventCell = $('<div class="container">'+addEvent+'</div>');
var select = $('select', addEventCell);
var oldId = select.attr('id');
var newId = oldId.split('_')[0] + '_' + (parseInt(oldId.split('_')[1]) + 1);
select.attr('id', newId).attr('name', newId);
$('section').append(addEventCell);
});
});
http://jsfiddle.net/QVYhu/
Related
I have a script which works fine only if input changes.
I want my script start working when the page loaded and then when input will change.
What is wrong with my script?
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
var pricevat = <?php echo $vat; ?>;
$('input[name=quantity]').on( 'input change', function(){
var productQty = parseFloat($(".to_overlock").val());
var meter = parseFloat($(".qty").val());
overlock = (((meter + productQty) *2) * pricevat).toFixed(2);
$('#price_overlock').val(overlock);
});
})
function my_val() {
var singleValues = $('#pa_shirina-rulona').val();
var stringNum = parseInt( singleValues );
$('#to_overlock').val(stringNum);
}
$('select').change(my_val);
my_val();
$(document).ready(function(){
$('input[name=quantity]').on( 'input change', function(){
var meters = parseFloat($(".to_overlock").val());
var qty = parseFloat($(".qty").val());
square = ((meters * qty)).toFixed(2);
$('#square').val(square);
});
})
</script>
Try with this quicly cleaned code.
You had two event handlers for the same selector and same events... I merged them.
And one $(document).ready() is enought to wrap everything.
The call to $('select').change(my_val); was not inside the ready handler... So maybe that was the issue...
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
var pricevat = <?php echo $vat; ?>;
$('input[name=quantity]').on( 'input change', function(){
var productQty = parseFloat($(".to_overlock").val());
var meters = parseFloat($(".qty").val());
var qty = parseFloat($(".qty").val());
var overlock = (((meters + productQty) *2) * pricevat).toFixed(2);
$('#price_overlock').val(overlock);
var square = ((meters * qty)).toFixed(2);
$('#square').val(square);
});
function my_val() {
var singleValues = $('#pa_shirina-rulona').val();
var stringNum = parseInt( singleValues );
$('#to_overlock').val(stringNum);
}
$('select').change(my_val);
my_val();
});
</script>
Thanks for all. I made triger for my page content id.
$(document).ready(function(){
var pricevat = <?php echo $vat; ?>;
$('#variator').on( 'change', function(e){
var productQty = parseFloat($(".to_overlock").val());
var meter = parseFloat($(".qty").val());
overlock = (((meter + productQty) *2) * pricevat).toFixed(2);
$('#price_overlock').val(overlock);
var meters = parseFloat($(".to_overlock").val());
var qty = parseFloat($(".qty").val());
square = ((meters * qty)).toFixed(2);
$('#square').val(square);
});})
function my_val() {
var singleValues = $('#pa_shirina-rulona').val();
var stringNum = parseInt( singleValues );
$('#to_overlock').val(stringNum);
}
$('select').change(my_val);
my_val();
You can trigger a change event on page load after you have initialized the event listener(s)
const $sel = $('select').on('change', function(){
$('input').val(this.value);
console.log('change triggered')
})
$sel.val('2').change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<input/>
i want to perform keyup event via textbox id, and all textbox are dynamically created with onclick button event. for this i have to make 20 keyup function. if i use 20 keyup function then my code will become too lengthy and complex. instead of this i want to use a common function for all textbox. can anybody suggest me how to do it..thanks
here is what i am doing to solve it:
<div class="input_fields_wrap">
<button class="add_field_button">Add Booking</button></div>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var counter = 2;
$(".add_field_button").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div id="target"><label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="firsttextbox' + counter + '" value="" > <input type="text" name="textbox' + counter +
'" id="secondtextbox' + counter + '" value="" > Remove<input type="text" id="box' + counter + '" value="">sum</div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
function check(a, b) {
var first = a;
var second = b;
var temp = temp;
var novalue = "";
result = parseInt(first) + parseInt(second);
if (!isNaN(result)) {
return result;
} else {
return novalue;
}
}
$(this).on("keyup", "#firsttextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
var number = 2;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#firsttextbox3", function(e) {
var number = 3;
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#firsttextbox4", function(e) {
var number = 4;
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
final = document.getElementById('box4').value = result;
});
$(this).on("keyup", "#secondtextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#secondtextbox3", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#secondtextbox4", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
document.getElementById('box4').value = result;
});
$(this).on("click", "#remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('#target').remove();
counter--;
});
});
</script>
See the snippet below to see how you can make this implementation more modular and useable. The trick is to think: what do I want to do? I want to be able to add multiple inputs and add their value, printing the result in another input.
It comes down to using classes - since we are going to use the same kind of thing for every row. Then apply something that works for all classes. No IDs whatsoever! You can even use the name property of the input that contains the value you want to save. Using the [] in that property will even pass you back a nice array when POSTING!
I know this looks like a daunting lot, but remove my comments and the number of lines reduces dramatically and this kind of code is almost infinitely extendable and reusable.
But have a look, this works and its simple and - most of all - it's DRY (don't repeat yourself 0 once you do, re-evaluate as there should be a better way!)!
Update
You could also use a <ol>as a wrapper and then add an <li> to this every time, so you get automatic counting of boxes in the front end without any effort from your end! Actually, thats so nice for this that I have changed my implementation.
var add = $('#add_boxes');
var all = $('#boxes');
var amountOfInputs = 2;
var maximumBoxes = 10;
add.click(function(event){
// create a limit
if($(".box").length >= maximumBoxes){
alert("You cannot have more than 10 boxes!");
return;
}
var listItem = $('<li class="box"></li>');
// we will add 2 boxes here, but we can modify this in the amountOfBoxes value
for(var i = 0; i < amountOfInputs; i++){
listItem.append('<input type="text" class="input" />');
}
listItem.append('<input type="text" class="output" name="value" />');
// Lets add a link to remove this group as well, with a removeGroup class
listItem.append('<input type="button" value="Remove" class="removeGroup" />')
listItem.appendTo(all);
});
// This will tie in ANY input you add to the page. I have added them with the class `input`, but you can use any class you want, as long as you target it correctly.
$(document).on("keyup", "input.input", function(event){
// Get the group
var group = $(this).parent();
// Get the children (all that arent the .output input)
var children = group.children("input:not(.output)");
// Get the input where you want to print the output
var output = group.children(".output");
// Set a value
var value = 0;
// Here we will run through every input and add its value
children.each(function(){
// Add the value of every box. If parseInt fails, add 0.
value += parseInt(this.value) || 0;
});
// Print the output value
output.val(value);
});
// Lets implement your remove field option by removing the groups parent div on click
$(document).on("click", ".removeGroup", function(event){
event.preventDefault();
$(this).parent(".box").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ol id="boxes">
</ol>
<input type="button" value="Add a row" id="add_boxes" />
You can target all your textboxes, present or future, whatever their number, with a simple function like this :
$(document).on("keyup", "input[type=text]", function(){
var $textbox = $(this);
console.log($textbox.val());
})
$("button").click(function(){
$("#container").append('<input type="text" /><br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="text" /><br>
<input type="text" /><br>
<input type="text" /><br>
</div>
<button>Create one more</button>
You don't need complicated generated IDs, not necessarily a class (except if you have other input[type=text] you don't want to conflict with). And you don't need to duplicate your code and write 20 times the same function. Ever. If you're duplicating code, you're doing wrong.
Add classes "a" and "b" to the textboxes and "box" to the box. Then add data-idx attribute with the index (unused!?). Finally register the event handlers:
$('.a').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= this.value;
var b= $p.find('.b').val()
var number =$this.data('idx') //unused!?
var result = check(a,b)
$p.find('.box').val(result)
})
$('.b').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= $p.find('.a').val()
var b= this.value
var result = check(a,b)
$p.find('.box').val(result)
})
Or a general one:
$('.a,.b').on('keyup', function(e){
e.preventDefault();
var $p = $(this).parent()
var a= $p.find('.a').val()
var b= $p.find('.b').val()
var result = check(a,b)
$p.find('.box').val(result)
})
You can assign a class to all textboxes on which you want to perform keyup event and than using this class you can attach the event on elements which have that class. Here is an example
var html="";
for (var i = 0; i < 20; i++)
{
html += "<input type='text' id='txt" + i + "' class='someClass' />";
}
$("#testDiv").html(html);
Attach keyup event on elements which have class someClass.
$(".someClass").keyup(function () {
alert($(this).attr("id"));
});
A little helper to combine with your favorite answer:
var uid = function () {
var id = 0;
return function () {
return ++id;
};
}();
Usage:
uid(); // 1
uid(); // 2
uid(); // 3
Providing a code-snippet which may give you some hint:
$(".add_field_button").click(function ()
{
if (counter > 10)
{
alert("Only 10 textboxes allow");
return false;
}
var txtBoxDiv = $("<div id='TextBoxDiv"+counter+"' style='float:left;width:10%; position:relative; margin-left:5px;' align='center'></div>");
//creating the risk weight
var txtBox1 = $('<input />',
{
'id' : 'fst_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox2 = $('<input />',
{
'id' : 'sec_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox3 = $('<input />',
{
'id' : 'sum_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
});
$(txtBoxDiv).append(txtBox1).append(txtBox2);
$(txtBoxDiv).append(txtBox3);
});
function txtBoxFun(obj, count)
{
var idGet = $(obj).attr('id');
var idArr = new Array();
idArr = idGet.split("_");
if(idArr[0] == "fst")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#sec_textbox_"+count).val()));
}
else if(idArr[0] == "sec")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#fst_textbox_"+count).val()));
}
$("#sum_textbox_"+count).val(sumTxt);
}
I have these functions:
$(".Read-Showing-Comment-Cancel").live('click', function (e) {
var guid = $(this).data("guid");
e.preventDefault();
var f = $('#comments-form-' + guid).slideUp();
$('comments-text-' + guid).empty();
$('comments-text-' + guid).value = "";
$(this).find('.comments-form-' + guid).hide();
$('comments-sendlink-' + guid).show();
});
$('.showComments').unbind('click').click(function (event) {
$('.ListingDisplayOptions').hide();
$(this).find('.comments-form-' + showGuid).show();
var showGuid = $(this).attr('rel');
loadShowingsComments(showGuid);
$(this).attr('id', 'comments-sendlink-' + showGuid);
event.preventDefault();
});
function loadShowingsComments(guid) {
var commentTextArea = "#comments-form-" + guid;
var commentDisplay = ".spanComments" + guid;
var curComment = $(commentDisplay).text();
var element = "#comments-form-" + guid;
$(element).slideDown();
}
<script>
function showComments() {
var comments = document.querySelectorAll(".spanComments");
for (var i = 0; i < comments.length; i++) {
comments[i].innerHTML = "This is comment #" + i;
}
}
</script>
View Comments
Those functions should grab the information from my controller (it's hooked up correctly. I've stepped through that and it has populated the right information) and place them in my span:
<tr class="p_la" id="comments-form-#currentShowing.ShowingGUID" style="display:none;">
<td colspan="4" style="border-right:5px solid #DDDDDD;">
<form action="" method="post">
<span class="spanComments" cols="100" rows="5">#string.Format("{0} / {1}", #currentShowing.Comments.DateAdded, #currentShowing.Comments.CommentsValue)</span>
<br />
Close
</form>
</td>
</tr>
Unfortunately, when I click on my hyperlink, it only populates the first span with the first span's information. Works great for the first span but when you click on the hyperlink in the second, third, fourth, etc item, they will only open up the first span with the first span's information.
The code should populate each successive span with its own information.
My JQuery was off. It needed this to be changed:
$(".Read-Showing-Comment-Cancel").live('click', function (e) {
var guid = $(this).data("guid");
e.preventDefault();
var f = $('#comments-form-' + guid).slideUp();
$('comments-text-' + guid).empty();
$('comments-text-' + guid).value = "";
$(this).parent("form").parent("td").parent("tr").hide();
$('comments-sendlink-' + guid).show();
});
$('.showComments').unbind('click').click(function (event) {
$('.ListingDisplayOptions').hide();
var showGuid = $(this).attr('rel');
$(this).parent("td").parent("tr").next('#comments-form-' + showGuid).show();
$(this).attr('id', 'comments-sendlink-' + showGuid);
event.preventDefault();
});
I'm having trouble filtering resulting div's with jQuery via two different inputs. Users can decide to filter by office, specialty or both office and specialty. The filtering is set from data attributes on the div that correspond to the select inputs values.
<div>
<label for="officeSearch">Search by office:</label>
<select name="Office Search" id="officeSearch">
<option value="all"></option>
<option value="communication">Communication</option>
<option value="internal medicine">Internal Medicine</option>
</select>
</div>
<div>
<label for="specialtySearch">Search by specialty:</label>
<select name="Specialty Search" id="specialtySearch">
<option value="all"></option>
<option value="Bone Cancer">Bone Cancer</option>
<option value="Breast Cancer">Breast Cancer</option>
<option value="Oral Cancer">Oral Cancer</option>
</select>
</div>
<div class="module-sm profile" data-office="communication" data-specialty="Oral Cancer">
<p>Person A</p>
</div>
<div class="module-sm profile" data-office="communication" data-specialty="Breast Cancer">
<p>Person B</p>
</div>
<div class="module-sm profile" data-office="internal medicine" data-specialty="Bone Cancer">
<p>Person C</p>
</div>
Here's the jQuery I'm using that fires on change of the selects:
$(document).ready(function() {
$("#officeSearch").on('change', function(){
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var person = $('#filterList .profile').not('.out');
var allPersons = $('#filterList .profile');
var allPersonsOffice = $('#filterList .profile').data('office');
var allPersonsOut = $('#filterList .profile.out');
var office = $('.profile[data-office="' + selectedOffice +'"]');
alert(''+ selectedOffice + ' ' + selectedSpecialty +'');
if (selectedOffice == 'all' && selectedSpecialty == 'all'){
$(allPersons).removeClass('out').fadeIn(500);
}
else {
$(person).not(office).addClass('out').fadeOut(500);
office.removeClass('out').fadeIn(500);
}
});
$("#specialtySearch").on('change', function(){
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var person = $('#filterList .profile').not('.out');
var allPersons = $('#filterList .profile');
var allPersonsOffice = $('#filterList .profile').data('office');
var allPersonsOut = $('#filterList .profile.out');
var specialty = $('.profile[data-specialty="' + selectedSpecialty +'"]');
alert(''+ selectedOffice + ' ' + selectedSpecialty +'');
if (selectedOffice == 'all' && selectedSpecialty == 'all'){
$(allPersons).removeClass('out').fadeIn(500);
}
else {
$(person).not(specialty).addClass('out').fadeOut(500);
specialty.removeClass('out').fadeIn(500);
}
});
});
If it helps, I've made a codepen to demonstrate what I'm trying to do and where I'm at so far.
I've done some searching and have been scratching my head on how to get this working for weeks. Any help making this code more concise or examples to how others have solved this problem are greatly appreciated!
Call a single update from either selection changing.
Create a filter based on the selections (appended).
Hide the ones not in the matches
show the matches.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/2u7NY/
$(document).ready(function () {
var onChange = function () {
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var filter = "#filterList .profile";
var allPersons = $(filter);
if (selectedOffice != "all")
{
filter += '[data-office="' + selectedOffice + '"]'
}
if (selectedSpecialty != "all")
{
filter += '[data-specialty="' + selectedSpecialty + '"]'
}
var $matching = allPersons.filter(filter);
$(allPersons).not($matching).removeClass('out').fadeOut(500);
$matching.removeClass('out').fadeIn(500);
}
$("#officeSearch, #specialtySearch").on('change', onChange );
});
Update: http://jsfiddle.net/TrueBlueAussie/2u7NY/2/
The filter can be made slightly more efficient as "#filterList .profile" is not needed to filter allPersons based on attributes.
I also removed the function variable and placed the function inline on the change event.
$(document).ready(function () {
$("#officeSearch, #specialtySearch").on('change',
function () {
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
var allPersons = $("#filterList .profile");
var filter = "";
if (selectedOffice != "all") {
filter = '[data-office="' + selectedOffice + '"]'
}
if (selectedSpecialty != "all") {
filter += '[data-specialty="' + selectedSpecialty + '"]'
}
var $matching = allPersons.filter(filter);
$(allPersons).not($matching).removeClass('out').fadeOut(500);
$matching.removeClass('out').fadeIn(500);
});
});
OK. Try something like this....
var match = function(office, specialty, profile) {
var show = ((office == 'all' || office == $(profile).data('office')) &&
(specialty == 'all' || specialty == $(profile).data('specialty')));
if (show && !$(profile).is(':visible')) {
$(profile).fadeIn();
}
if (!show && $(profile).is(':visible')) {
$(profile).fadeOut();
}
}
var filter = function() {
var selectedOffice = $('#officeSearch').val();
var selectedSpecialty = $('#specialtySearch').val();
$.each($('#filterList .profile'), function(i, profile) {
match(selectedOffice, selectedSpecialty, profile);
});
};
$("#officeSearch").on('change', function(){
filter();
});
$("#specialtySearch").on('change', function(){
filter();
});
working fiddle here.... http://jsfiddle.net/6Q8FF/
I want after add a input and remove it, arrange the numbers in input name element array by jQuery but don't work for me after remove input. How can fix it?
DEMO: http://jsfiddle.net/mUMdW/
My Code:
Html:
<div class="ch">
Add
</div>
<p class="ffdd"></p>
jQuery:
function removeidx(clss, type){
var remove = $(this).closest(clss);
remove.fadeOut('slow', function () {
$(this).remove(); // or change next line to $('.RowCheck:visible')
$(clss).each(function (idx) {
var checkBoxes = $('input[type="'+type+'"]',this);
checkBoxes.each(function(i) {
var str = $(this).attr('name');
var currentIdx = parseInt(str.match(/\d+/)[0], 10);
$(this).attr('name', str.replace(currentIdx,idx));
})
});
});
}
$(document).on('click change', 'a.adding', function(e) {
e.preventDefault();
var idx = $('.Row').length;
$('.ffdd').append('<div class="Row"> <input name="arr['+idx+'][]" type="text" value=""> Remove</div>');
});
$('.ffdd').on('click','a', function(e){
$(this).closest('.Row').remove();
removeidx('.ffdd', 'text');
})
I guess that you want to re-number the inputs after a remove, so that the array is made of contiguous numbers.
I have rewritten some things, among which the renumbering function, using an index contextual to the parent function.
function removeidx(context, clss, type) {
var remove = $(context).closest(clss);
remove.fadeOut('slow', function () {
$(this).remove();
var idx = 0;
$(clss).each(function () {
var checkBoxes = $('input[type="' + type + '"]', this);
checkBoxes.each(function () {
var name = $(this).attr('name');
name = name.replace(/\d+/, idx);
$(this).attr('name', name);
idx = idx + 1;
});
});
});
}
$(document).on('click change', 'a.adding', function (e) {
e.preventDefault();
var idx = $('.Row').length;
$('.ffdd').append('<div class="Row"> <input name="arr[' + idx + '][]" type="text" value=""> Remove</div>');
});
$('.ffdd').on('click', 'a', function (e) {
removeidx(this, '.Row', 'text');
})
You can see a working version there : http://jsfiddle.net/8sVWp/