jquery removing string parts from two areas - javascript

I'm looking to expand on a recent script i've coded using jquery.
I have this following code
<script type='text/javascript'>
added_departments = new Array();
$("#departments_submit").click(function(){
var depo = $("#depo_list").val();
if(jQuery.inArray(depo, added_departments) != -1)
{
return false;
}
else
{
added_departments.push(depo);
$("#depo_added_list").append("<li>" + depo + "<a href='#' title='"+ depo +"' class='remove_depo'> [X] </a></li>");
var current_value = $("#departments").val();
if(current_value)
{
$("#departments").val(current_value + "," + depo);
}
else
{
$("#departments").val(depo);
}
return false;
}
});
</script>
The above code takes information selected in a select drop down box, adds it to a div to display publicly and also into a hidden form field that processes the data.
i've tried to create now something that will reverse this effect and remove certain selections from the div and the field. which is where i have this code
<script type='text/javascript'>
$(".remove_depo").click(function(){
var removing = $(this).title();
var current_val = $("#deparments").val();
if(current_val == removing) {
$("departments").replace(removing, "");
}
else {
$("departments").replace("," + removing, "");
}
});
</script>
It doesn't cause any errors, but it doesn't do anything either? So I'm really stuck. Any ideas?
EDIT: Updated code
$(".remove_depo").click(function(){
var removing = $(this).attr('title');
var current_val = $("#deparments").val();
if(current_val == removing) {
$("#departments").replace(removing, "");
}
else {
$("#departments").replace("," + removing, "");
}
});
Here is the html
<form method="post" action="javascript:void(0);">Select Departments To Be Added:
<div class="depo_adder">
<select id="depo_list"><option value="">--- INDIVIDUAL TAGS ---</option><option value="blah">blah</option></select>
<button id="departments_submit">Go!</button>
</div></form><form method="post" action="briefings/addbriefing.php">
<div class="form">
<strong>Departments: </strong>
<ul id="depo_added_list"><li>blah [X] </li></ul>
<input name="departments" id="departments" value="blah" type="hidden">
</div>

you're referring to $('departments') - this won't work. You need to specify either an identifierm eg $('#departments') or a class, eg $('.departments)
ah - other answer is also correct, .title() is not a function. You want
$('#foo').attr('title') to get the title.

Related

HTML / JQuery: Email an Entire Div/Table

I want to be able to email content such as a div that is in my webpage using the php mail function and possible putting it on the so called "Thank Your, Your Email Sent" page. However, I'm running into some issues. I am following this Email Div Content, Email div text content using PHP mail function, and GET entire div with its elements and send it with php mail function questions that has already been posted as a guide but it doesn't seem to be working for me. I want to send via email and show up on the "Thank Your, Your Email Sent" page within the message. Anything I'm doing wrong?
HTML Table that I want to send over is:
<div id="add_items_content" style="width:100%;">
<center>
<table id="add_item_here" style="width:98%;">
<tbody>
<tr><td>Item</td><td>Years</td><td>Quantity</td><td>Training Hours</td><td>Total Item Cost</td></tr>
</tbody>
</table>
</center>
<center>
<table id="add_totals_here" style="width:98%;">
<tbody>
<tr><td cospan="3"> </td><td> </td><td> </td></tr>
</tbody>
</table>
</center>
</div>
<script>
$(document).ready(function(){
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
$('div[id^=show_form]').hide();
//First obtaining indexes for each checkbox that is checked
$('input[name=item_chk]').change(function(){
var index = this.id.replace('item_chk','');
if($(this).is(':checked')){
AddNewItem(index);
}else{
RemoveItem(index);
}
CalculateTotals();
});
function AddNewItem(index){
// Get hidden variables to use for calculation and tables.
var item = $('#item_chk'+index).parent().text().trim();
var itemdescr = $('#itemdescr'+index).val();
var traininghrs = parseInt($('#traininghrs'+index).val());
var qty = parseInt($('#qty'+index).val());
var yrs = parseInt($('#yrs'+index).val());
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
//Display each item that is checked into a table
$('#add_item_here tr:last').after('<tr id="row_id'+index + '"><td style=\"width:35%;\">' + itemdescr +'</td><td style=\"width:15%;\" >' + yrs +'</td><td style=\"width:16%;\">' + qty +'</td><td style=\"width:18%;\">' + traininghrs + '</td><td style=\"width:16%;\">$'+ item_cost + '</td></tr>');
}
function RemoveItem(index){
$('table#add_item_here tr#row_id'+index).remove();
}
function CalculateTotals(){
var total_cost = 0;
var total_training = 0;
$('input:checkbox:checked').each(function(){
var index = this.id.replace('item_chk','');
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
total_cost +=item_cost;
total_training +=traininghrs;
});
if(total_cost > 0 || total_training > 0) {
$('#add_totals_here tr:last').children().remove();
$('#add_totals_here tr:last').after('<tr ><td colspan="3" style=\"width:66%;\">TOTALS:</td><td style=\"width:18%;\">' + total_training + '</td><td style=\"width:16%;\">$'+ total_cost + '</td></tr>');
$('#add_item_here').show();
$('#add_totals_here').show();
$('#office_submit').show();
}else{
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
}
}
$("input[name='office_submit']").click(function () {
$('#show_form').css('display', ($(this).val() === 'Yes') ? 'block':'none');
});
// Quantity change, if someone changes the quantity
$('select[name=qty]').change(function(){
var index = this.id.replace('qty','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
// Years change, if someone changes the years
$('select[name=yrs]').change(function(){
var index = this.id.replace('yrs','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
})
</script>
Trial Number 1; So far I have tried:
<script>
function mail_content() {
var tablesContent = document.getElementById("add_items_content").innerHTML;
$.post('send_form.email.php',{content:tablecontent},function(data) {
});
}
</script>
Using script I have added to the send_form_email.php:
<?php
$txt = $_POST['content'];
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
?>
Trial Number 2: I even tried storing it into a hidden field:
<input name="data" id="data" type="hidden" value=""></input>
<script type="text/javascript">
$(document).ready(function(){
$("#price_quote").submit(function() { //notice submit event
$("#my_hidden_field").val($("#add_items_content").html()); //notice html function instead of text();
});
});
</script>
And then the send_form_email.php I put it in that message see if it even shows up.
$txt = $_POST['data'];
$message = "Content: ".$txt."\n";
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
Trial Number 3: Even tried Ajax
<script>
function mail_content(){
var html = $('#add_items_content').html();
$.ajax(function{
type="POST",
url:"send_form_email.php",
data:"data="+html,
success:function(response){
$('#add_items_content').show().html("email sent");
}
});
}
</script>
What am I missing or doing wrong? Why doesn't the div / tables show up or display?
You really should check your JS console for errors:
var tablesContent = document.getElementById("add_items_content").innerHTML;
^---note the "sC"
$.post('send_form.email.php',{content:tablecontent},function(data) {
^--note the c
JS vars are case sensitive, and will NOT magically correct typos for you.
And then there's this:
<input name="data" id="data" type="hidden" value=""></input>
^---id 'data'
$("#my_hidden_field").val($("#add_items_content").html());
^--- completely DIFFERENT ID

Find next text by search and highlight not works

When search any text on search box, it can be find and highlighted the correct text, but when search next/new text, it's unable to find the next/new text, it's not working when search again, i'm unable to find the issue. The JS below.
JS
$('button#search').click(function() {
var page = $('#ray-all_text');
var pageText = page.html().replace("<span>", "").replace("</span>");
var searchedText = $('#searchfor').val();
var theRegEx = new RegExp("(" + searchedText + ")", "igm");
var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
page.html(newHtml);
$('html, body').animate({
scrollTop: $("#ray-all_text span").offset().top }, 2000);
});
HTML
<div class="ray-search">
<div class="field" id="ray-search-form">
<input type="text" id="searchfor" placeholder="what are you searching for?" />
<button type="button" id="search">Press to Find!</button>
</div>
</div>
<article id="ray-all_text">
<p>
This manual and web site, all information and data and photos contained herein, are the s...
</p>
</article>
Please check the live Example: https://jsfiddle.net/gaezs6s8
Why is this happening? Is there a solution?
My suggestion is to make a few validations before change all the .html() inside the text you want to avoid unexpected behaviors and improve the functionality.
First make a validation to avoid the 'space' as the first value on the input, this will let us later check if the input has a real value inside.
$('body').on('keydown', '#searchfor', function(e) {
if (e.which === 32 && e.target.selectionStart === 0) {
return false;
}
});
Code from this answer
Now Please check the comments on your code:
//Create some vars to later check for:
//['text you are searching', 'number of highlights','actual highlight']
var searching,
limitsearch,
countsearch;
$('button#search').click(function() {
var searchedText = $('#searchfor').val();
var page = $('#ray-all_text');
//Now check if the text on input is valid
if (searchedText != "") {
//If the actual text on the input is different from the prev search
if(searching != searchedText) {
page.find('span').contents().unwrap();
var pageText = page.html();
var theRegEx = new RegExp("(" + searchedText + ")", "igm");
var newHtml = pageText.replace(theRegEx, "<span>$1</span>");
page.html(newHtml);
//Set your variables to the actual search
searching = searchedText;
limitsearch = page.find('span').length;
countsearch=0;
} else {
//If it's the same of the prev search then move to next item instead of repaint html
countsearch<limitsearch-1 ? countsearch++ : countsearch=0;
console.log(countsearch+'---'+limitsearch)
}
//Go to target search
$('body').animate({
scrollTop: $("#ray-all_text span").eq(countsearch).offset().top - 50},
200);
} else {
alert('empty search')
}
});
JqueryDemo

Set option val based on array

I am trying to build a search that uses multiple drop downs. The script for the search uses the values for the first drop down and the second drop down. It works correct for Acura and MDX, but if I choose RLX it still passes MDX to the search as the value.
I know I have so somehow set for the value for the appended option to be whatever array is chosen in the second drop down, but I have had no luck. I am new to javascript so for all I know there may be a way easier than this to accomplish my goal.
FORM FOR SUBMIT
<form name="searchform" onSubmit="return dosearch();">
Brand:
<select id="brands">
<option val="Acura">Acura</option>
<option val="Chrysler">Chrysler</option>
</select>
<select id="item">
</select>
<input type="submit" value="Submit">
</form>
SCRIPT FOR URL STARTING WITH A BASE URL
<script type="text/javascript">
function dosearch() {
var sf=document.searchform;
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
location.href = baseUrl.concat('make='+ sf.brands.options[sf.brands.selectedIndex].value + '&&&&' + 'model=' + sf.item.options[sf.brands.selectedIndex].value + '&&&&' );
return false;
}
SCRIPT FOR DROP DOWNS
// JavaScript Document
$(document).ready(function(){
Acura=new Array("MDX","RLX","ILX","TLX");
Chrysler=new Array('200','3000','Town&Country');
populateSelect();
$(function() {
$('#brands').change(function(){
populateSelect();
});
});
function populateSelect(){
cat=$('#brands').val();
$('#item').html('');
eval(cat).forEach(function(t) {
$('#item').append('<option val="">'+t+'</option>');
});
}
});
Wow wow!
Please read some code style for js. If it works it doesnt mean that it's good.
DO NOT USE eval, EVER! eval = evil
You forgetting var declaration.
Inline handler in html bad practice too.
forEach will break in IE <= 8
concat is good, plus is good too
... lot of mistakes, that will cost you after.
I`ve wrote you a one liner, but it doesnt have structure. Just some ideas and removed a lot of things.
http://jsfiddle.net/gwEP5/
Whole js code:
$(function (){
// Selector
var $form = $("#searchform");
// it could be hashchange in the future
var setPath = function (url) {
window.location = url;
};
var searchHandler = function (e) {
e.preventDefault();
// You can serialize whole form just by .serialize
var url = window.location.pathname + "?" + $form.serialize();
setPath(url);
};
// Handlers, set handlers in js not in DOM, inline delegation is really nasty
// alias for .submit
$form.on("submit", searchHandler);
// Form elements
var $brands = $('#brands'),
$item = $("#item");
// Items list, dont use new Array or String. It`s good way in
var items = {
"Acura": ["MDX","RLX","ILX","TLX"],
"Chrysler": ['200','3000','Town&Country']
};
// eval is EVIL !!!! don`t use it ever
var populateItems = function () {
var elements = "",
value = $brands.val();
if (items[value] != null) {
$.each(items[value], function (i, item) {
elements += "<option value=\"" + item + "\">" + item + "</option>";
});
}
$item.html(elements);
}
// Alias .change
$brands.on("change", populateItems);
// init for start
populateItems();
});
Html form:
<form name="searchform" id="searchform">
Brand:
<select id="brands" name="make">
<option value="Acura">Acura</option>
<option value="Chrysler">Chrysler</option>
</select>
<select id="item" name="model">
</select>
<input type="submit" value="Submit"/>
</form>
The setup itself is fine. However, you have a typo:
sf.item.options[sf.brands.selectedIndex]
Should be:
sf.item.options[sf.item.selectedIndex]
Or, if you prefer the more aesthetic jQuery:
function dosearch() {
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
var brand = $('#brands').find(":selected").text();
var item = $('#item').find(":selected").text();
location.href = baseUrl + 'make=' + brand + '&&&&' + 'model=' + item + '&&&&';
return false;
}

Prototype - spiceworks bulk close tickets select

I am looking for guidance to look for a way to accomplish some difficulty in programming that I don't have the experience to create.
I am using Spiceworks with a custom plugin called Plugin Bulk Delete and Close and it works fine but I need an additional logic. I have a custom attribute called Master Number where I can specify relations on tickets screenshot.
I'm looking for a way that in case a ticket is selected to close all with the same Master Number. Well, my programming is very limited and I just started with prototype and reading about jquery for a month and a half now. Any help or direction is all I need this is possibly very simple but not for me.
SPICEWORKS.app.helpdesk.ready(function(){
if(document.URL.indexOf("Master_View") >= 0){
if ($('Multi-Toolbar') === null)
{
var toolbarDInsert = '<a class="delete toolbar_buton" href="#" id="plugin-Dactions">';
var toolbarCInsert = '<a class="clopen toolbar_buton" href="#" id="plugin-Cactions"><span class="inner icon">Close/Open Ticket(s)</span></a>';
var cbInsert = '<span style="float:left;"><input type="checkbox" class="plugin-operation" name="cbselection" /></span>';
var HdInsert = 'div#ticket-list-body table tr td.cell-status';
var thinsert = '<div id="Multi-Toolbar" class="sui-toolbar"><tr><th><input type="checkbox" id="plugin-all" /></th></tr></div>';
plugin.includeStyles();
$('primary').insert({top:thinsert});
$('Multi-Toolbar').insert(toolbarCInsert);
$('Multi-Toolbar').insert(toolbarDInsert);
var insertcheckbox = function(actions){
actions.style.width = '2.5em';
actions.insert({top:cbInsert});
};
$$(HdInsert).each(insertcheckbox);
$('plugin-Cactions').observe('click', function(event){
event.stop();
var entries = $$('input.plugin-operation').select(function(input){
return input.checked;
}).collect(function(input){
return input.up('tr').id.replace('ticket-', '');
});
if(entries.size() > 0){
var answer = confirm('You are about to Close / Open ' + entries.size() + ' Ticket(s) Relying on the Ticket(s) state. \nContinue ?') ;
if (answer){
entries.each(function(entry){ new Ajax.Request('/tickets/toggle_status/' + entry);
});
}}
if(entries.size() <= 0){
alert('No ticket(s) selected, please select at least one ticket');
}
});
$('plugin-all').observe('click',function (e) {
var toggle = $('plugin-all').checked;
$$('div#ticket-list-body input[type=checkbox]').each(function(check) {
check.checked = toggle;
});
});
}
}
});

deleting dynamically added DOM elements in IE6

My problem is that the DELETE ITEM (Item which has been added dynamically) is not deleteing by click in IE6.
javascript:
var TDCount = 3;
var i=0;
function insertTD(){
var possition=document.getElementById('elmnt_pos').value;
if(possition=="")
{
possition='a';
alert('Enter a number!!!');
}
if(isNaN(possition))
{
alert('Enter a number!!!');
document.getElementById('elmnt_pos').value='';
}else{
var newTD = document.createElement("li");
var newid='li'+TDCount++;
newTD.setAttribute("id", newid);
newTD.setAttribute("onclick","javascript:removenode(this);" );
var newText = document.createTextNode(i+"New fruit " + (possition++));
newTD.appendChild(newText);
var trElm = document.getElementById("menu");
var refTD = trElm.getElementsByTagName("li").item(possition-2);
trElm.insertBefore(newTD,refTD);
i++;
}
}
function removenode(th)
{
answer = confirm("Do you really want to Remove Element "+th.id + " ? ")
if (answer !=0)
{
document.getElementById('menu').removeChild(document.getElementById(th.id));
}
}
html
<ul id="menu">
<li id="li0" onclick="javascript:removenode(this);">apple</li>
<li id="li1" onclick="javascript:removenode(this);">Banana</li>
<li id="li2" onclick="javascript:removenode(this);">Jackfruit</li>
</ul>
<form name="justfrm">
<input type="text" value="Enter the position" name="pos1" id="elmnt_pos" />
<input type="button" value="click" onclick="javascript:insertTD()"/>
</form>
"Enter the position" means add element on a specific position like 2,3,5 etc.
We can Delete Item by click on item .
I don't have an instance on Internet Explorer 6 to test with, but more than likely it's this line, which is causing the problem:
newTD.setAttribute("onclick","javascript:removenode(this);" );
It does not work in Internet Explorer 6. You will need to do something like:
newTD.onclick = function() { removeNode(this); };
or
newTD.onclick = new Function("removenode(this)");
See this article for more information. Also, as a side note you may want to look into using a library like jQuery, which already handles these types of cross-browser issues.

Categories

Resources