I have the following code.
I want the id of selected checkbox of my prescriptionid div tag only.
I have written the jQuery code but I did not get the correct output. The jquery code is shown below. I want to append the selected checkbox id to my hidden textbox.
<div class="form-group" id="prescriptionid">
<!-- <label for="cid" class="col-lg-2 col-sm-2 control-label">Patient ID</label> -->
<div class="col-lg-10">
<% for (int i=0 ; i < testpre.size(); i++) { if(testpre.get(i).getTest_prescription_id()<11) { %>
<input type="checkbox" name="chk<%=testpre.get(i).getTest_prescription_id()%>" id="<%=testpre.get(i).getTest_prescription_id()%>" value="<%=testpre.get(i).getTest_prescription_name() %>">
<%=testpre.get(i).getTest_prescription_name() %>
<br>
<% } else { %>
<input type="checkbox" name="chk<%=testpre.get(i).getTest_prescription_id() %>" id="<%=testpre.get(i).getTest_prescription_id()%>" value="<%=testpre.get(i).getTest_prescription_name() %>" class="diab">
<%=testpre.get(i).getTest_prescription_name() %>
<br>
<% } %>
<% } %>
</div>
</div>
jQuery code
$(document).ready(function () {
var someObj = {};
someObj.chkArray = [];
$("#prescriptionid").click(function () {
var $this = $(this);
someObj.chkArray.push($this.attr("id"));
alert("Handler for .click() called.");
alert("GRANTED: " + someObj.chkArray);
});
});
Try this:
$(document).ready(function () {
var someObj = {};
someObj.chkArray = [];
$("#prescriptionid input[type=checkbox]").click(function () { // to target the checkbox i added input[type=checkbox]
someObj.chkArray.push(this.id); // this.id is enought, no need for $(this).attr('id')
alert("Handler for .click() called.");
alert("GRANTED: " + someObj.chkArray[0]); // I don't think you need a array, but anyway to show in the alert I added [0]
});
});
One easy solution is to construct the checked array every time from the source
$(document).ready(function () {
var someObj = {};
someObj.chkArray = [];
var $checks = $('#prescriptionid input[type="checkbox"]').change(function () {
var ids = $checks.filter(':checked').map(function () {
returnt this.id
}).get();
alert("Handler for .click() called.");
alert("GRANTED: " + ids);
someObj.chkArray = ids;
});
});
Blockquote i done your requirement. Check the following link page show the demo
enter link description here
$(document).ready(function () {
$( "#prescriptionid" ).click(function() {
var someObj="";
$('input[type="checkbox"]:checked').each(function() {
if(someObj=="")
someObj = this.id;
else
someObj = someObj+","+this.id;
});
//alert(someObj);
$("#sel").val(someObj) ;
});
});
Related
I have a number of textareas and when I click on a paragraph outside the text is supposed to be added to the textarea, it works but the text is also getting added to the textareas above.
I'm a bit stumped on why this is happening and as I have 10 textaraes so clicking a paragraph at the bottom of the page adds the text to all the other textareas above.
Javascript
$(document).ready(function () {
$("#PollutionPreventionDivScrollDisplay").hide();
$("#PollutionPreventionDivScroll").on("click", function () {
$("#PollutionPreventionDivScrollDisplay").toggle();
});
var cartlist = document.querySelector("#EnvironmentalActionPollutionPreventionIdeasForAction");
var items = document.querySelectorAll("[data-item]");
[].forEach.call(items, function (item) {
item.addEventListener("click", function (e) {
e.preventDefault();
cartlist.value += `\n${item.innerHTML}`;
});
});
});
$(document).ready(function () {
$("#WasteDivScrollDisplay").hide();
$("#WasteDivScrollDisplayScroll").on("click", function () {
$("#WasteDivScrollDisplay").toggle();
});
var cartlistOne = document.querySelector("#EnvironmentalActionWasteManagementIdeasForAction");
var itemsOne = document.querySelectorAll("[data-item]");
[].forEach.call(itemsOne,
function (itemOne) {
itemOne.addEventListener("click", function (e) {
e.preventDefault();
cartlistOne.value += `\n${itemOne.innerHTML}`;
});
});
});
$(document).ready(function () {
$("#EnergyDivScrollDisplay").hide();
$("#EnergyDivScrollDisplayScroll").on("click", function () {
$("#EnergyDivScrollDisplay").toggle();
});
var cartlistTwo = document.querySelector("#EnvironmentalActionEnergyIdeasForAction");
var itemsTwo = document.querySelectorAll("[data-item]");
[].forEach.call(itemsTwo,
function (itemTwo) {
itemTwo.addEventListener("click", function (c) {
c.preventDefault();
cartlistTwo.value += `\n${itemTwo.innerHTML}`;
});
});
});
Example of html
<div class="row">
<div id="PollutionPreventionDivScrollDisplay" class="col-md-12 border-colour fixed-height">
#foreach (var info in Model.EnvironmentalActionPollutionPreventionExtraInfo)
{
var countItems = counter++;
<p><a data-item="#countItems" href="#">#info</a></p>
}
</div>
</div>
<div class="col-md-4 border-colour-right">
<div class="form-group">
<span class="mouse-pointer text-danger" id="PollutionPreventionDivScroll">Click to add options</span>
<label class="sr-only" for="EnvironmentalActionPollutionPreventionIdeasForActionPlaceholder">Environmental Action Pollution Prevention Ideas For Action</label>
#Html.TextAreaFor(x => x.EnvironmentalActionPollutionPreventionIdeasForAction, new { Class = "form-control", Placeholder = Model.EnvironmentalActionPollutionPreventionIdeasForActionPlaceholder, rows = "8" })
</div>
</div>
All other code is the same except the sames are different
Ok silly mistake, I had all 'data-item' the same should have been 'data-item-one', 'data-item-two' etc
I know this question has been asked a million times, but I can't seem to get anything to work. I am trying to have the value of the input change when I click one of the links which is working fine, but I'd also like to submit the form automatically as well, without a submit button as soon as a link is clicked. At the moment it doesn't work unless I click the input field. Also I can't add id's to the links. This is what I have so far.
var $Form = $('form'), $Container = $('#container');
$Container.hide();
$Form.on('click', function(p_oEvent){
var sUrl, sMovie, oData;
p_oEvent.preventDefault();
sMovie = $Form.find('input').val();
sUrl = 'https://www.omdbapi.com/?t=' + sMovie + ''
$.ajax(sUrl, {
complete: function(p_oXHR, p_sStatus){
oData = $.parseJSON(p_oXHR.responseText);
console.log(oData);
$Container.find('.title').text(oData.Title);
$Container.find('.plot').text(oData.Plot);
$Container.find('.poster').html('<img src="' + oData.Poster +
'"/>');
$Container.find('.year').text(oData.Year);
$Container.show();
}
});
});
$(function () {
$('a').on('click', function () {
var text = $('#text');
text.val($(this).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
rocky<br>
Back To The Future<br>
Spaceballs<br>
<form id="omdbform">
<input type="text" name="movie" placeholder="movie title" id="text" onchange="this.form.submit();">
</form>
<div id="container">
<h3 class="title">Title</h3>
<span class="year">Year</span>
<span class="poster">Poster</span>
<p class="plot">Plot</p>
</div>
Any help would be greatly appreciated.
Added link examples
filename1.jpg
filename2.jpeg
Change your link function to below :
$(function () {
$('a').on('click', function () {
var text = $('#text');
var fileName =$(this).text();
fileName = fileName.replace(/\.[^/.]+$/, "");
text.val(fileName);
$Form.click();
});
});
try the following code
var $Form = $('form')
$Container = $('#container');
$Container.hide();
$("body").on("submit", "form", function(p_oEvent){
var sUrl, sMovie, oData;
p_oEvent.preventDefault(); sMovie = $Form.find('input').val();
sUrl = 'https://www.omdbapi.com/?t=' + sMovie + ''
$.ajax(sUrl, {
complete: function(p_oXHR, p_sStatus){
oData = $.parseJSON(p_oXHR.responseText);
console.log(oData);
$Container.find('.title').text(oData.Title);
$Container.find('.plot').text(oData.Plot);
$Container.find('.poster').html('<img src="' + oData.Poster +
'"/>');
$Container.find('.year').text(oData.Year);
$Container.show();
}
}); });
$('a').on('click', function (e) {
e.preventDefault();
var text = $('#text');
text.val($(this).text());
$("form").submit();
});
Before using the "on" read http://api.jquery.com/on/
I want to be able to add jquery UI to the list on GoalNotes This table gets populated by what the user enters in the "name1" and "data1" input fields. Every time I give the an id, the program breaks and I get no errors. Any ideas on how I could apply animations to the table rows that get added after the user inputs data?
html
<section class="section section--active color1" data-letter="M">
<article class="section__wrapper">
<h1 class="section__title">Monday</h1>
<div id="Monday" class="tabcontent">
<form name="goalsList1" action = "/created" method="POST">
<div id="tab1">
<table>
<tr>
<td><b>New Goal:</b><input type="text" name="name1" id="name1"></td>
<td><b>Notes:</b><input type="text" name="data1" id="data1"></td>
<td>
<input type="submit" value="Save" onclick="SaveItem(1)">
</td>
</tr>
</table>
</div>
<div id="items_table1">
<h2>List of goals</h2>
<table id="list1" contenteditable> </table>
<p>
<label><input type="button" value="Clear" onclick="ClearAll(1)"></label>
</p>
</div>
</form>
</div>
</article>
</section>
javascript
function doShowAll(numOfWeek) {
if (CheckBrowser()) {
var key = "";
var list = "**<tr><th>Goal</th><th>Notes</th></tr>**\n";
var i = 0;
var goals = localStorage[numOfWeek] ? JSON.parse(localStorage[numOfWeek]) : {};
var goalsKeys = Object.keys(goals);
for (i = 0; i < goalsKeys.length; i++) {
key = goalsKeys[i];
list += "<tr><td>" + key + "</td>\n<td>"
+ goals[key] + "</td></tr>\n";
}
if (list == "<tr><th>Goal</th><th>Notes</th></tr>\n") {
list += "<tr><td><i>nothin' here</i></td>\n<td><i>nothin' here either</i></td></tr>\n";
}
document.getElementById('list'+numOfWeek).innerHTML = list;
} else {
alert('Cannot store list as your browser do not support local storage');
}
}
$(document).ready(function(e) {
$('#due-date').datepicker();
$('#add-todo').button({
icons: {
primary: "ui-icon-circle-plus"
}
}).click(function() {
$('#new-todo').dialog('open');
}); // end click
$('#new-todo').dialog({
modal: true,
autoOpen: false,
close: function() {
$('#new-todo input').val(''); /*clear fields*/
},
buttons : {
"Add task" : function() {
var taskName = $('#task').val();
var dueDate = $('#due-date').val();
var beginLi = '<li><span class="done">%</span><span class="delete">x</span>';
var taskLi = '<span class="task">' + taskName + '</span>';
var dateLi = '<span class="due-date">' + dueDate + '</span>';
var endLi = '</li>';
$('#todo-list').prepend(beginLi + taskLi + dateLi + endLi);
$('#todo-list').hide().slideDown(250).find('li:first')
.animate({
'background-color': '#ff99c2'
},250)
.animate({
'background-color': '#d9b3ff'
},250).animate; // end animate
$(this).dialog('close');
},
"Cancel" : function() {
$(this).dialog('close');
}
}
});
$('#todo-list').on('click','.done',function(e) {
var $taskItem = $(this).parent("li");
var $copy = $taskItem.clone();
$('#completed-list').prepend($copy);
$copy.hide().slideDown();
$taskItem.remove();
}
); // end on
$('#todo-list, #completed-list').on('click','.delete',function(e) {
$(this).parent("li").slideUp(250, function() {
$(this).remove();
}); // end slideup
}); // end on
$('#todo-list').sortable();
}); // end ready
http://jsbin.com/digefufeca/edit?html,css,js,console,output
The problem
The form with nane goalsList1 is sending whenever you click on the button.
Why? because the button is submit button.
The solution(s)
Replace the button's type to button. (link)
Prevent the form submission by event.preventDefault(). (link)
There are more ways but those are the major.
Note: your code still not working but now you can see the error message.
I'm using a jquery to add a new checkbox when I click an option from an existing checkbox.
Next I add an id in this checkbox and I get it's value through a new jquery. I want to create a new jquery to get the ids of ALL the extended checked ids.
My current html code is:
<div id="div_id_diag-diagnosis_option" class="form-group">
<label for="id_diag-diagnosis_option_0" class="control-label col-md-3 requiredField">Option<span class="asteriskField">*</span> </label>
<div class="controls col-md-8">
<label class="checkbox">
<input type="checkbox" name="diag-diagnosis_option" id="id_diag-diagnosis_option_1" value="b">b</label>
<label class="checkbox">
<input type="checkbox" name="diag-diagnosis_option" id="id_diag-diagnosis_option_2" value="a">a</label>
<label class="checkbox">
<input type="checkbox" name="diag-diagnosis_option" id="id_diag-diagnosis_option_3" value="c">c</label>
</div>
</div>
The jquery to add the checkbox is:
$("input[name='diag-diagnosis_option']").change(function() {
var $this = $(this);
if ($this.prop('checked')) {
var option = $(this).val();
alert(option);
$(this).parent().append("<a href='#'>here</a>");
} else if ($this.siblings('a').length) {
$this.siblings('a').remove();
}
});
The jquery to get the value of the new checkbox is the one below:
$(document).on('change', '#extended', function () {
var option = $(this).val();
//alert(option);
});
The jquery to get the ids of all the extended checked checkboxes is the one below but it's not working.
var selected = [];
$(document).on('each', '#extended input:checked', function () {
selected.push($(this).attr('id'));
alert(selected);
});
You can test it here.
Can you help me please?
You have incorrect syntax for iterating over checkboxes. You are trying to use each as an event. However each is jquery method and not even associated to element. and correct syntax to use it is:
var selected = [];
$('#extended input:checked').each(function () {
selected.push($(this).attr('name'));
alert(selected);
});
However you can achieve this in cleaner way using .map() along with .get() to achieve this:
var selected = $('#extended input:checked').map(function(){
return $(this).attr('name');
}).get();
EDIT
As you append checkboxes dynamically , you should add values at there change event .. also you have dynamic checkboxes with same id .. you should use class instead of id that is not permitted
Do it as-
var selected = [];
$("input[name='diag-diagnosis_option']").change(function () {
var $this = $(this)
if ($(this).prop('checked')) {
var option = $(this).val();
$(this).parent().append('<label><input type="checkbox" class="extended"
name="extended" value=' + escape($(this).attr('value')) + '>
Extended</label>');
} else if ($this.siblings('label').length) {
$this.siblings('label').remove();
}
});
$(document).on('change', '.extended', function () {
var option = $(this).val(); // or attr('name');
selected.push(option);
alert(selected);
});
LIVE https://jsfiddle.net/mailmerohit5/wt9btcb0/
I'm trying to create a simple "search field", what it does is it searches if typed in text is equal to any data-attr of the boxes in the content and if so, hide everything but what found, something similar (this ain't working):
css:
.filter-div {
display: none;
}
html:
<label for="search">Search Input:</label>
<input type="search" name="filter" id="search" value="" />
<div class="filter-div" data-filter="one">one</div>
<div class="filter-div" data-filter="two">two</div>
<div class="filter-div" data-filter="three">three</div>
<div class="filter-div" data-filter="four">four</div>
<div class="filter-div" data-filter="five">five</div>
jquery:
// save the default value on page load
var filter = $('.input').val();
// on submit, compare
if ( $('.input').val() = $("data-filter") {
$(this).show();
}
I am also not sure if the content should be filtered with a button click or found content should pop up as click-able text in the search, or should all happen auto? Finally probably I will have to check it against more than one data-attr.
Anyone?
$('#search').on('keyup', function() {
var val = $.trim(this.value);
if (val) {
$('div[data-filter=' + val + ']').show();
} else $('div[data-filter]').hide();
});
Working sample
According to demo fiddle example in comment
var divs = $('div[data-filter]');
$('#search').on('keyup', function() {
var val = $.trim(this.value);
divs.hide();
divs.filter(function() {
return $(this).data('filter').search(val) >= 0
}).show();
});
divs.on('click', function() {
divs.not(this).hide();
var text = $.trim($(this).text());
$('#search').val(text);
});
Working sample
JavaScript:
var filter_div = $('[data-filter]');
$('#search').keyup(function(){
var val = $.trim(this.value);
filter_div.hide();
if(val.length == 0) return;
filter_div.filter(function(){
return $(this).data('filter').indexOf(val)>-1
}).show();
});
Fiddle: http://jsfiddle.net/iambriansreed/xMwS5/