Add a checkbox for the innerHTML in javascript - javascript

I have a page which contains a 10 items(formatted list).Here in this page I need to add check box for each item and add the item as the value to each check box.when the user click on the check box the selected value should be passed to a new page.Can anyone help me how to add a check box for the innerHTML in java script.
Code:
var newsletter=document.getElementById("block-system-main");
var districolumn=getElementsByClassName('view-id-_create_a_news_letter_',newsletter,'div');
if(districolumn!=null)
{
var newsletterall=newsletter.getElementsByTagName('li');
alert(newsletterall[0].innerHTML);
var all=newsletter.innerHTML;
newsletter.innerHTML="<input type='button' onclick='changeText()' value='Change Text'/>";
}
function changeText()
{
alert("dfgsdg");
}

I don't exactly understand what each part of your code is doing, but i'll try and give a general answer:
In your HTML, do something like this:
<form id="myForm" action="nextPage.com">
<div id="Boxes"></div>
</form>
Change the above names to wherever you want your checkboxes to be written.
And your function:
function changeText()
{
for(var i=0 ; i < newsletterall.length ; i++)
{
var inner = document.getElementById("Boxes").innerHTML;
var newBox = ('<input type="checkbox" name="item[]" value="' + newsletter[i] + '>' + newsletterall[i]);
document.getElementById("Boxes").innerHTML = inner + newBox;
}
document.getElementById("myForm").submit();
}
The last line of code submits the checkboxes automatically. If you don't want that, remove that line, and add a submit button to the form myForm.

​
$('ul​​​#list li').each(
function() {
var me = $(this),
val = me.html(),
ckb = $('<input type="checkbox" />');
ckb.click(function() {
var where=val;
window.location.href='http://google.com/?'+where;
});
me.html('');
me.append(ckb).append($('<span>'+val+'</span>'));
}
);​​​​

Related

Checkbox check event is not getting prevented

I have a set of set of checkboxes on which I want to restrict to check maximum of one. If the choice needs to be changed then first checked ones need to be unchecked but maximum limit needs to be one.
Here is the jquery code.
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var checkedReportValues = $('#ReportRow input:checkbox:checked').map(function () {
return this.value;
}).get();
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
alert(checkedReportValues);
})
);
Here, the above code is restricting only one checkbox to be checked but when I am trying to check other, they first are being checked and then unchecked. Where I am doing wrong ?
Here is the dynamically created HTML.
//Add Code to Create CheckBox dynamically by accessing data from Ajax for the application selected above
var Reports = " User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += ' <label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label>';
}
//Add Submit button here
reportscheckBoxhtml += ' <button type="button" id="SubmitReport" class="btn btn-primary">Submit</button>';
$('#ReportRow').html(reportscheckBoxhtml);
Try this: uncheck all other checkboxes except clicked one inside click event handler, like below
$('#ReportRow').on('click', 'input[type="checkbox"]',function(){
$('#ReportRow input[type="checkbox"]').not(this).prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ReportRow">
<input type="checkbox">one
<input type="checkbox">Two
<input type="checkbox">Three
<input type="checkbox">Four
</div>
This line:
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
is saying you want to uncheck the checkbox. It's doing exactly what you tell it to do. Just a comment: Users may be confused since checkboxes are meant to check multiple selections. Radio buttons are designed for being able to select only one option.
you are returning false from the function when there is a checkbox already selected, which is preventing the checkbox selection.
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
Do something like this:
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var curCheckBox = this;
$('#ReportRow').find('input[type="checkbox"]').each(function() {
if(this === curCheckBox)
$(this).attr("checked",true);
else
$(this).attr("checked",false);
});
alert(checkedReportValues);
});

Adding input forms and removing them again get all id's

I'm currently adding some input fields to a div. There is also the option to remove the just added input fields.
Now the problem is, if you add 4 input fields and let's say you removed number 2.
You will get something like this
id=1
id=3
id=4
Now when you will add a new one it will add id=5.
So we end up with:
id=1
id=3
id=4
id=5
JS :
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
console.log(historyVar);
});
HTML :
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
For now it's okay.
Now for the next part I'm trying to get the data from the input fields:
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
How can I make sure to get the data of all the input fields?
Working version
You could do with a whole lot less code. For example purposes I'm going to keep it more simple than your question, but the priciple remains the same:
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
The bracket at the end make it an array. We do not use any numbers in the name.
When you submit, it will get their index because it´s an array, which returns something like:
$_POST['artiestnaam'] = array(
[0] => "whatever you typed in the first",
[1] => "whatever you typed in the second",
[2] => "whatever you typed in the third"
)
If I would add and delete a hundred inputs, kept 3 random inputs and submit that, it will still be that result. The code will do the counting for you.
Nice bonus: If you add some javascript which enables to change the order of the inputs, it will be in the order the user placed them (e.g. if I had changed nuymber 2 and 3, my result would be "one, third, second").
Working fiddle
You could use each() function to go through all the divs with class js-artist:
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
Hope this helps.
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
console.log(historyVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
Initialize a count variable. This way if an input field is removed, a new id still gets initialized. To get the data for each of them, jQuery has a convenient each function to iterate over all elements.
Hope this helps
count = 0;
$("#add").on("click", function() {
count++;
$("body").append("<input id='" + count + "'</input>");
});
$("#remove").on("click", function() {
var index = prompt("Enter the index of the input you want to remove");
$("input:eq(" + index + ")").remove();
});
$("#log-data").on("click", function() {
$("input").each(function() {
console.log($(this).val());
});
});
#btn-group {
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn-group">
<button id="add">Add Input Fields</button>
<button id="remove">Remove Input Fields</button>
<button id="log-data">Log Data</button>
</div>

jQuery input forms issue

I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});

how to make button insert tag in a textfield?

I'm trying to make multiple buttons that when clicked they add tags like <p></p> and <b></b> to a text-field. I have already figured out how to make it work like this:
<script>
function addtxt(input) {
var obj=document.getElementById(input)
obj.value+="<p></p>"
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body')">
but instead of having multiple scripts for every different button, I'd like to know if there is a way of the JS use the element value as obj.value. Is it possible?
EDIT: i found this other code online that's even better, how can i make this new code use the element value, is there any way?
function boldText(textAreaId, link)
{
var browser=navigator.appName
var b_version=navigator.appVersion
if (browser=="Microsoft Internet Explorer" && b_version>='4')
{
var str = document.selection.createRange().text;
document.getElementById(textAreaId).focus();
var sel = document.selection.createRange();
sel.text = "<b>" + str + "</b>";
return;
}
field = document.getElementById(textAreaId);
startPos = field.selectionStart;
endPos = field.selectionEnd;
before = field.value.substr(0, startPos);
selected = field.value.substr(field.selectionStart, (field.selectionEnd - field.selectionStart));
after = field.value.substr(field.selectionEnd, (field.value.length - field.selectionEnd));
field.value = before + "<b>" + selected + "</b>" + after;
}
You may pass this to your onclick handler, and then access it's value within your function:
<script>
function addtxt(input, button) {
var obj=document.getElementById(input);
obj.value+=button.value;
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body', this)">
<input type="button" value="<b></b>" onclick="addtxt('body', this)">
Here is an example with a specific div that receives the code javascript produces.
I don't recomend adding it to a div with id body, because that word is reserved for html structural elements, so I called the destination div "addHere".
Javascript
function addtxt(e) {
console.log(e)
var dest = document.getElementById("addHere");
dest.innerHTML = e.value;
}
HTML
<input type="button" value="<p>Text</p>" onclick="addtxt(this)">
<div id="addHere"></div>
fiddle here

Same function for different sections - relative referencing in jquery

By using relative references I am able to remove items which have been added to the list within a specfic part of the form. For example, by adding a requirement it can be deleted just from the requirement.
My issue is two fold:
Adding an item to references adds it to all three categories
When I try to add values to the other sections (qualifications) it says my input was blank.
http://jsfiddle.net/spadez/9sX6X/60/
var container = $('.copies'),
value_src = $('#current'),
maxFields = 10,
currentFields = 1;
$('.form').on('click', '.add', function () {
value_src.focus();
if ($.trim(value_src.val()) != '') {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
value_src.focus();
$(this).parents('.line').remove();
currentFields--;
});
Is it possible to modify this code without repeating it for each section, by using relatively references such as "parent" for example. I want to use this same script for all three sections but have it so each list is independant.
I'm new to javascript so I was wondering if this is possible because I only managed to get it working on the delete.
You have to use this to get the current element. In your case this refers to the button which was clicked.
The next step is to get the input box which belongs to the button. E.g. $(this).prev(); like in this example:
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
http://jsfiddle.net/9sX6X/62/
The same is also true for your appending part. Your are appending your html to all three elements which match $('.copies'). Instead you have to try to get there from this.
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var copies = $(this).parent().prev();
http://jsfiddle.net/9sX6X/63/
I would suggest adding a wrapping div to each section.
<div class="section">
<h4>Requirements</h4>
<div class="copies"></div>
<div class="line">
<input id="current" type="text" name="content" placeholder="Requirement" />
<input type="button" value="Add" class="add" />
</div>
</div>
Then you can do this:
var $section = $(this).closest(".section");
$(html).appendTo($section.find(".copies"));
This will add to just the related .copies element instead of to all .copies as your code does now. A similar approach can be used for all other elements as well.

Categories