Include jQuery in JavaScript - javascript

I've got two bits of code that I'd like to work together but I don't manage to integrate this jQuery snippet into the JavaScript correctly …
JavaScript:
(function(){
// Creates the plugin
tinymce.create('tinymce.plugins.mygallery', {
// Creates control instances based on the control's ID.
createControl : function(id, controlManager) {
if (id == 'mygallery_button') {
// Creates the button
var button = controlManager.createButton('mygallery_button', {
title : 'MyGallery Shortcode', // Title of the button
image : '../wp-includes/images/smilies/icon_mrgreen.gif', // Path to the button's image
onclick : function() {
// Triggers the thickbox
var width = jQuery(window).width(), H = jQuery(window).height(), W = ( 720 < width ) ? 720 : width;
W = W - 80;
H = H - 184;
tb_show( 'My Gallery Shortcode', '#TB_inline?width=' + W + '&height=' + H + '&inlineId=mygallery-form' );
}
});
return button;
}
return null;
}
});
// Registers the plugin
tinymce.PluginManager.add('mygallery', tinymce.plugins.mygallery);
// Executes this when the DOM is ready
jQuery(function(){
// Creates a form to be displayed everytime the button is clicked
var form = jQuery('<div id="mygallery-form"><table id="mygallery-table" class="form-table">\
<form id="myForm">\
<div id="input1" style="margin-bottom:4px;" class="clonedInput">\
Name: <input type="text" name="name1" id="name1" />\
</div>\
<div>\
<input type="button" id="btnAdd" value="add another name" />\
<input type="button" id="btnDel" value="remove name" />\
</div>\
</form>\
</div>');
[…]
});
})()
jQuery:
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
FYI: The JS creates a popup with a form (WordPress) and with the jQuery snippet I'd like to implement the feature that the user can add more input fields dynamically.
Thanks for your help!

You can put the jQuery snippet after your javascript code. That shouldn't be the problem since your jQuery code is merely binding events.
However, I can't tell where #btnAdd and #btnDel are. The problem may be that the elements are created after the jQuery code is run, hence when you called this:
$('#btnAdd').click(function(){...});
the element #btnAdd was not there.
Try this:
$(document).on('click', '#btnAdd', function(){...});
This will bind the click event to document (which is always present) instead of #btnAdd.
To improve the performance though, you should bind it to a parent of #btnAdd that you know for sure is present when document is ready.

Related

I want to add a element with prepend jQuery

I want to add a new a element when I click the button but it doesnt work
<div id="add-container">
<input type="text"> <button>add</button>
<div id="megobrebi">
<a>Levani</a>
<a>Markozi</a>
<a>Zuka</a>
<a>Sandro</a>
</div>
</div>
$(document).ready(function() {
$('#add-container').on('click', 'button', function(){
var value = $('#add-container input').val;
var html = '<a>' + value + '</a>'
$('$megobrebi').prepend(html);
})
})
You have two errors in the handler for the click event on the button.
First, you need to call the jQuery val method in order to get the value of the input.
Second, the selector for the DOM element where you want to prepend is not right.
Therefore, the code should be:
$('#add-container').on('click', 'button', function(){
var value = $('#add-container input').val();
var html = '<a>' + value + '</a>'
$('#megobrebi').prepend(html);
})
The last line should be
$('#megobrebi').prepend(html);
Change your script code to
$(document).ready(function() {
$('#add-container button').on('click', function(e){
e.preventDefault(); // You may use this line if you wish to disable the default functionality button.
var value = $('#add-container input').val();
var html = '<a>' + value + '</a>';
$('#megobrebi').prepend(html);
});
});

How to select a dynamically generated form element in jquery / javascript using its ID?

I am trying to create a row of 3 form fields dynamically when the user clicks on the ADD button / plus symbol .
Javascript code used to create the form elements is below :
<script type="text/javascript">
var field_counter = 1;
var field_limit = 5;
species = document.getElementById('species');
breed = document.getElementById('breed');
function addInput(divName){
if (field_counter == field_limit) {
alert("You have reached the limit of adding " + field_counter + " inputs");
}
else {
var dynamic_species = 'species'+field_counter; //dynamic id for species
var dynamic_breed = 'breed'+field_counter; //dynamic id for breed
var dynamic_quantity = 'quantity'+field_counter; //dynammic id for quantity
var dynamicForm = '<div class="form-group"><div class="col-md-4"><label for="'+dynamic_species+'">Animal Type</label><select class="form-control input-sm '+dynamic_species+'" id="'+dynamic_species+'"><option></option></select></div>';
dynamicForm+='<div class="form-group"><div class="col-md-4"><label for="'+dynamic_breed+'">Breed</label><select class="form-control input-sm '+dynamic_breed+'" id="'+dynamic_breed+'"><option></option></select></div>';
dynamicForm+='<div class="form-group"><div class="col-md-2"><label for="'+dynamic_quantity+'">Quantity</label><input type="number" name="quantity_export" id="'+dynamic_quantity+'" class="form-control input-sm '+dynamic_quantity+'" /></div>';
var newdiv = document.createElement('div');
newdiv.innerHTML = dynamicForm;
document.getElementById(divName).appendChild(newdiv);
document.getElementById(dynamic_species).innerHTML = species.innerHTML;
document.getElementById(dynamic_breed).innerHTML = breed.innerHTML;
field_counter++;
}
}
</script>
<div class="col-md-2" >
<label for=""> </label>
<i onclick="addInput('dynamicInput');" style="cursor: pointer; border: none;" class="fa fa-plus form-control input-sm">Add</i>
</div>
Using the above code am creating the form fields "Animal Type , Breed and Quantity ", all together in a row as shown in the image . Maximum number of rows that can be added is limited to the value of the variable "field_limit".
The value of the drop downs are initially populated from the parent drop down using the code :
species = document.getElementById('species');
breed = document.getElementById('breed');
document.getElementById(dynamic_species).innerHTML = species.innerHTML;
document.getElementById(dynamic_breed).innerHTML = breed.innerHTML;
Question : How can I select the dynamically generated ID of the new form fields .
Here is the script am using to select the first row of form fields which is in the HTML when the page loads for the first time :
$("#species").change(function(){
$('#breed').empty();
//alert($(this).val());
var param = {'id':$(this).val()};
$.ajax({
type : 'POST',
url : '<?php echo base_url();?>select_breed',
dataType : 'json',
data: param,
success : function(data)
{
var select = $('#breed');
select.empty().append(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown)
{
alert(XMLHttpRequest.responseText);
}
});
});
The second row of form fields are created dynamically with the following ID's
First Field : Animal Type : ID="species1"
Second Field : Breed : ID="breed1"
Third Field : Quantity : ID="quantity1"
I am not able to select the dynamically generated form fields using the jquery selector :- eg: $("#species1").change(function(){}); , it is not working .
What I am trying to do ?
I need to get the value of these fields using its ID attribute. Any help would be highly appreciated . Thank you .
Use event delegation for dynamic generated content like so :
// change `document` to top level parent that existed on page or
// parent container
$(document).on("change", "#species1", function(){...});
Thats because they do not exists yet when binding to it's change event.
You could add the event listener in the add_input function, or use a more abstract event handler:
$("form").on("change", ".species", function () {
var id = $(this).attr("data-id");
...
});
This will require you to drop the ID's and use class attributes instead. Which is the way to go by my opinion.
You can attach the ID's using $(speciesElement).attr("data-id", id).

Simple two button counter html jquery javascript

I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days.
I saw this tutorial:
http://www.codecademy.com/courses/a-simple-counter/0/1
I completed the tutorial and thought: "I should learn how to do this with Jquery".
So I've been trying to use what I understand to do so. My issue is that I don't know how to pass an argument for a variable from HTML to Jquery(javascript).
Here is my code:
HTML
<body>
<label for="qty">Quantity</label>
<input id="qty" type = "number" value = 0 />
<button class = "botton">-1</button>
<button class = "botton">+1</button>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
Jquery/Javascript:
//create a function that adds or subtracts based on the button pressed
function modify_qty(x) {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = $('#qty').val();
var new_qty = qty + x;
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').html(new_qty)
})
};
$(document).ready(modify_qty);
How do I pass an argument of 1 or -1 to the function? I was using onClick() but that seemed redundant because of the $('.botton').click(function(){}).
Thank you
If you use data attributes on your buttons you can get the value you want.
HTML:
<button class = "botton" data-value="-1">-1</button>
<button class = "botton" data-value="1">+1</button>
JS:
function modify_qty() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var qty = parseInt($('#qty').val());
var new_qty = qty + parseInt($(this).data('value'));
//i don't want to go below 0
if (new_qty < 0) {
new_qty = 0;
}
//put new value into input box id-'qty'
$('#qty').val(new_qty)
})
};
$(document).ready(modify_qty);
More compact JS:
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val());
$qty.val(Math.max(0, currentValue + parseInt($(this).data('value'))));
})
});
Update:
Realized you could do this without the data attributes if want to since your button text is the same as your value.
$(function() {
//on click add or subtract
$('.botton').click(function(){
//get the value of input field id-'qty'
var $qty = $('#qty'),
currentValue = parseInt($qty.val()),
newValue = currentValue + parseInt($(this).text());
$qty.val(Math.max(0, newValue));
})
});
Here's a fiddle to help you grasp the what's going on. Basically, the reference to the element that triggered the event is $(this) or event.target. Things get a bit more complicated with self refence depending on the context you are in, however for $('selector').on('event',function(event){ console.log($(this)) //is the reference to $('selector') });. .attr() -> list of the element's attributes.

jQuery onclick add textbox value to div using the ID's

I am trying to add some textbox value to some other divs.
What I'd like to obtain is somthing like this:
textbox id = "text-box-name-1" ----> div id = "div-name-1"
textbox id = "text-box-name-2" ----> div id = "div-name-2"
textbox id = "text-box-name-3" ----> div id = "div-name-3"
and so on....
How can i do this? mind that the number of divs and textboxes are dynamically generated.!
Any suggestion will be really appreciated.
Thanks
EDIT
function test() {
var rooms = $("#howmanyrooms").val();
var roomcounter = 1;
for (var i = 0; i < rooms; i++) {
$("<div class='appendeddiv'>Room-" + roomcounter++ + "</div>").appendTo(".housecontainer");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id'></div></br>").appendTo(".infoncontainer");
};
if ($('.housecontainer').find('.appendeddiv').length) {
$("#buttonaddrooms").hide();
}
};
i have already this code that allows me to create as many divs and textboxes as i type inside the textbox as value.
Now, i want be able to set, for example as div title, what the user type inside the textbox, and the only way that i've thought till now is using the id that are dynamically generated by the code that i already have.
Thanks for editing the post...
I would suggest first to add one class as an identifier to the Textbox and Div so we can attach event with the help of jQuery
$("<div class='appendeddiv targetDiv_"+ roomcounter +"'>Room-" + roomcounter + "</div>").appendTo(".housecontainer");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id' lang='textInput' class='targetText_"+ roomcounter +"'></div></br>").appendTo(".infoncontainer");
After that following script will do the trick :)
<script type='text/javascript>
$(function(){
$("input.textInput").on("keyup",function(){
var target = $(this).attr("lang").replace("Text", "Div");
$("."+target).text($(this).val());
});
});
</script>
As per your fiddle If you want to update value mannualy onclick of any button then write this method.
<script type='text/javascript'>
function update(){
$("input.textInput").each(function(){
var target = $(this).attr("lang").replace("Text", "Div");
$("."+target).text($(this).val());
});
}
</script>

Generate jQuery form fields along with sno in a label

I need a form to generate form elements dynamically. So far I have modified a script to add another field txtEmail1 and it works fine and generates fields once a user hits the add button.
Now I need to prefix label "Full Name" with serial no. 1, 2, 3, 4 and so on. I tried but I am not able to get it right need an experts help with this.
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
newElem.children(':first').attr('id', 'txtEmail' + newNum).attr('txtEmail', 'txtEmail' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
</head>
<body>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<label id="lblSno1"></label> Full Name
<input name="name1" type="text" class="TextBoxNext" id="name1" /></td>
<input name="txtEmail1" type="text" class="TextBoxNext" id="txtEmail1" /></td>
</div>
</form>
</body>
I also need to assign the count to some hidden field, so that I can run an insert query on the number of fields that the user created.
Try something like the following. I've made a few modifications to the structure of your code, namely:
* Creating a hidden template that all visible clones will be cloned from
* Getting the add/remove buttons working as desired
* Added hidden field which holds the number of items
* Putting bulk of code into functions for re-use
<script type="text/javascript">
// document - on load
$(document).ready(function() {
// add the first item
AddInput();
UpdateButtons();
// add button - click
$('#btnAdd').click(function() {
AddInput();
UpdateButtons();
});
// delete button - click
$('#btnDel').click(function() {
$('.clonedInput:last').remove();
UpdateButtons();
});
});
function AddInput()
{
// how many cloned input fields we currently have
var numItems = $('.clonedInput').length;
var newNum = new Number(numItems + 1);
// create the new element via clone() based on hidden template
var newElem = $('.templateInput').clone();
// update attributes on parent tag
newElem.attr('id', 'input' + newNum);
newElem.attr('class', 'clonedInput');
newElem.show();
// update child elements
newElem.children('#lblSno').html(newNum + ' ' + newElem.children('#lblSno').html());
newElem.children('#lblSno').attr('id', 'lblSno' + newNum);
newElem.children('#name').attr('id', 'name' + newNum);
newElem.children('#txtEmail').attr('id', 'txtEmail' + newNum);
// insert the new element
$('#allInputs').append(newElem);
}
function UpdateButtons()
{
// get number of items
var numItems = $('.clonedInput').length;
// only enable delete button when there is more than 1 item
if (numItems > 1)
$('#btnDel').removeAttr('disabled');
else
$('#btnDel').attr('disabled', 'disabled');
// only enable add button when there are less than 5 items
if (numItems < 5)
$('#btnAdd').removeAttr('disabled');
else
$('#btnAdd').attr('disabled', 'disabled');
// update the hidden field
$('#hdnNumItems').val(numItems);
}
</script>
<form>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
<input type="hidden" id="hdnNumItems" value="0" />
</div>
<div id="allInputs">
<div class="templateInput" style="margin-bottom:4px; display:none;">
<label id="lblSno">Full Name</label>
<input name="name" type="text" class="TextBoxNext" id="name1" /></td>
<input name="txtEmail" type="text" class="TextBoxNext" id="txtEmail1" /></td>
</div>
<div>
</form>
There are thousands of ways to do what you are trying to do, and it's all entirely depends upon your choice which one to use. So, without messing with your logic and simply going with your own code, in order to add serial numbers, just add this one line :
newElem.text(newNum + " ) Full Name " );
That's it. You've got your serial number prepended.

Categories