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
Related
given this html snippet
<div id="imageSelection" class="form-group">
#Html.LabelFor(m => m.PostedFiles,"Select images/videos" ,new {id="fileSelect",#for="fileElem", #class="form-control btn btn-sm btn-success", style="width:144px;" })
#Html.TextBoxFor(m => m.PostedFiles, new
{
type = "file",
id = "fileElem",
#class = "col-md-10 form-control",
style="display:none;",
multiple = "multiple",
accept = "image/*",
onchange = "handleFiles(this.files)"
})
</div>
which works fine, you click the button, the file picker opens, you select some files and click the button to close the file picker. The onchange event is not firing (onchange is the event suggested by the example here)
It generates this html in the page
<div id="imageSelection" class="form-group">
<label class="form-control btn btn-sm btn-success" for="fileElem" id="fileSelect" style="width:144px;">Select images/videos</label>
<input accept="image/*" class="col-md-10 form-control" id="fileElem" multiple="multiple" name="PostedFiles" onchange="handleFiles(this.files)" style="display:none;" type="file" value="" />
</div>
Here is the script
<script>
$(document)
.ready(function () {
//element variables for the thumbnail display
var dropbox = $("#dropbox"),
filePropertyDisplay = $("#loadingImageFileProperties"),
fileName = $("#dd_filename"),
fileSize = $("#dd_filesize"),
fileType = $("#dd_filetype"),
gallery = $("#imageGallery"),
uploading = $("#imageUploading"),
fileSelect = document.getElementById("fileSelect"), //$("#fileSelect"),
fileElem = document.getElementById("fileElem"), //$("#fileElem"),
messages = $("#messageArea");
gallery.hide();
uploading.hide();
//add event listeners to handle events
dropbox.on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("dragover", function (e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("drop", function (e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
handleFiles(files);
});
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
//fileSelect.on("click", function (e) {
// if (fileElem) {
// fileElem.click();
// }
// // prevent navigation to "#"
// e.preventDefault();
//});
function handleFiles(files) {
alert(files.length);
}
});
</script>
I originally was trying to stick with JQuery but couldn't get that to work with .on() either, so i reverted back to Javascript, per the example, but that doesn't work either.
The drop functionality works, and calls handleFiles but the fileElem onchange method doesn't fire.
EDIT:
Sorry that made me realize that the problem was reading the files you've selected instead of just getting the code to work.
I've just added:
var files = $(this)[0].files;
To get the files collection the user selected (it could be one or more);
and then:
for (var i = 0; i < files.length; i++) {
alert(files[i].name);
}
loop through all the files selected and just get the name of it. You can also read .size if you need to.
This will the proper way to handle what you are trying to achieve.
$(document)
.ready(function () {
//element variables for the thumbnail display
var dropbox = $("#dropbox"),
filePropertyDisplay = $("#loadingImageFileProperties"),
fileName = $("#dd_filename"),
fileSize = $("#dd_filesize"),
fileType = $("#dd_filetype"),
gallery = $("#imageGallery"),
uploading = $("#imageUploading"),
fileSelect = document.getElementById("fileSelect"), //$("#fileSelect"),
fileElem = document.getElementById("fileElem"), //$("#fileElem"),
messages = $("#messageArea");
gallery.hide();
uploading.hide();
//add event listeners to handle events
dropbox.on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("dragover", function (e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("drop", function (e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
handleFiles(files);
});
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
$('#fileElem').on('change',function(e){
var files = $(this)[0].files;
for (var i = 0; i < files.length; i++) {
alert(files[i].name);
//alert(files[i].size);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imageSelection" class="form-group">
<label for="fileElem" class="form-control btn btn-sm btn-success", style="width:144px;" id="fileSelect">Select images/videos</label>
<input type="file" id = "fileElem" class = "col-md-10 form-control"
style="display:none;"
multiple = "multiple"
accept = "image/*"
</div>
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 have multi-selection functionality similar to this (see link): http://jsfiddle.net/eUDRV/341/.
HTML code:
<section class="container" >
<div>
<select id="list" name="list"size="15">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<div>
<br><br><br>
<input type="button" id="button_left" value="<--"/>
<input type="button" id="button_right" value="-->" />
</div>
<div>
<select id="selected_values" size="15"></select>
<input name="selected_values" type="hidden"/>
</div>
jQuery/Javascript code:
$(document).ready(function () {
$("#button_right").click(function () {
var selectedItem = $("#list option:selected");
var added = false;
$("#selected_values > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#selected_values"));
updateHiddenField();
});
$("#button_left").click(function () {
var selectedItem = $("#selected_values option:selected"), activeValues;
var added = false;
$("#list > option").each(function() {
if ($(this).text() > $(selectedItem).text()) {
$(selectedItem).insertBefore($(this));
added = true;
return false;
}
});
if(!added) $(selectedItem).appendTo($("#list"));
updateHiddenField();
});
function updateHiddenField () {
$('input[name="selected_values"]').val(
$.map($('#selected_values option:selected').toArray(), function (e) {
return e.value;
})
);
}
});
PHP code:
if(!empty($_POST['selected_values'])) {
$_POST['selected_values'] = explode(',', $_POST['selected_values']);
foreach($_POST['selected_values'] as $x) {
$query = "INSERT INTO $table (id1, id2) VALUES ($id1Value, $x)";
db_query($query);
My goal is to iterate through all of the values that are moved into the left column and enter them into a database using PHP. I'm able to get this functionality to work, however, I'm having the exact same issue as seen referenced here: how can I get all options in a multi-options select using PHP?. I'm accessing the values using $_POST["leftValues"] but if the user clicks on one of the options, only that one will be entered into the database. Unfortunately, the accepted solution isn't working for me.
$("form:has(#leftValues)").on('submit', function () {
$("#leftValues option").prop('selected', true);
});
Can someone please explain to me how I can get this solution to work for me or an alternative way of ensuring $_POST["leftValues"] will contain all the options instead of only the selected/highlighted? Any response is greatly appreciated.
You could add a hidden field and update that whenever the lists change.
You'd need to update your html:
<div>
<select id="leftValues" size="5" multiple></select>
<input name="leftValues" type="hidden" />
</div>
and add a function to do the updating:
function updateHiddenField () {
$('input[name="leftValues[]"]').val(
$.map($('#leftValues option:selected').toArray(), function (e) {
return e.value;
})
);
}
And call it in each of your click handlers:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
updateHiddenField();
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected"), activeValues;
$("#rightValues").append(selectedItem);
updateHiddenField();
});
Finally, you can do this in your PHP to get what you originally expected:
$_POST['leftValues'] = explode(',', $_POST['leftValues']);
Finally got it to work. I edited the submit callback, as the original solution suggested.
Added an id to my form tag:
<form id="form" method="post">
When the form is submitted, select/highlight all options in the selected_values list:
$(#form).submit(function () {
$("#selected_values > option").each(function () {
$(this).attr('selected', 'selected');
});
return true;
});
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) ;
});
});
Select element has selected value 4 (for example), I send form data to the server. The controller return partial view.
<script>
$(document).ready(function () {
var objSel = document.getElementById("IDVacationApplicationType");
checkVacationType(objSel);
$("select#IDVacationApplicationType").change(function () {
checkVacationType(this);
});
});
function checkVacationType(elem) {
var item = $(elem).val();
alert(item);
}
</script>
html:
<div class="form-position">
<div class="form-label">
#Html.LabelFor(model => model.VacationApplicationTypes)
</div>
<div class="form-value">
#Html.DropDownListFor(model => model.IDVacationApplicationType, Model.VacationApplicationTypes)
#Html.ValidationMessageFor(model => model.VacationApplicationTypes)
</div>
</div>
alert shows -1. After that form has select element with selected value = 4. How can I get this 4?
Answer: I had two the same ID in the page.
You can use this
$('#IDVacationApplicationType').find(":selected").val();
So change your function as checkVacationType as
function checkVacationType(elem) {
var item = $(elem).find(":selected").val();
alert(item);
}
Fiddle Demo
I had two the same ID in the page.
I need add class to the element:
#Html.DropDownListFor(model => model.IDVacationApplicationType, Model.VacationApplicationTypes, new { #class = "IDVacationApplicationType" })
<script>
$(document).ready(function () {
var objSel = $(".IDVacationApplicationType");
checkVacationType(objSel);
$(".IDVacationApplicationType").change(function () {
checkVacationType(this);
});
});
function checkVacationType(elem) {
var item = $(elem).val();
alert(item);
}
</script>