Update SQL Server Database On Table Edit/Change - javascript

I have a dynamic HTML table that can be edited in multiple ways. There is an edit button where you can edit inline, the information of the rows and then click save to save the information. A deactivate button that grays out the row and an activate button that appears afterwards in order to reactivate it. And also and add row button that brings up a dialog box where you can hit add row again and add another row to the table.
However, while that is all nice...I want to write these changes/updates to a SQL Server database now so it actually saves them. I want to be able to automatically save these changes after each action (save, deactivate/activate, and add row) happens. I have never done this before so any help/advice/code would be appreciated!
JavaScript code:
// ----- Deactivate/Activate Row -----
$(document).on("click", "#html_master .deactivate", function () {
var $this = $(this);
var $tr = $this.closest('tr');
var action = $tr.hasClass('deactivated') ? 'activate' : 'deactivate';
// ------ Confirmation box in order to deactivate/activate row -----
if (confirm('Are you sure you want to ' + action + ' this entry?')) {
$tr.toggleClass('deactivated');
$this.val(function (i, t) {
return t == 'Deactivate' ? 'Activate' : 'Deactivate';
});
}
});
// ----- Edit Row -----
$(document).on("click", "#html_master .edit", function () {
var $this = $(this);
var tds = $this.closest('tr').find('td').not('.mr_id').filter(function () {
return $(this).find('.edit').length === 0;
});
if ($this.val() === 'Edit') {
$this.val('Save');
tds.prop('contenteditable', true);
} else {
var isValid = true;
var errors = '';
$('#myDialogBox').empty();
// changed from here.......
var elements = tds;
if (tds.find('input').length > 0) {
elements = tds.find('input');
}
elements.each(function (index, element) {
var type = $(this).attr('class');
var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
// changed from here....... to here
// ----- Switch statement that provides validation -----
switch (type) {
case "buyer_id":
if (!$.isNumeric(value)) {
isValid = false;
errors += "Please enter a valid Buyer ID\n";
}
break;
case "poc_n":
if (value == value.match(/^[a-zA-Z\s]+$/)) {
break;
}
else {
isValid = false;
errors += "Please enter a valid Name\n";
}
break;
case "poc_e":
if (value == value.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)) {
break;
}
else {
isValid = false;
errors += "Please enter a valid Email\n";
}
break;
case "poc_p":
if (value == value.match('^[0-9 ()+/-]{10,}$')) {
break;
}
else {
isValid = false;
errors += "Please enter a valid Phone Number\n";
}
break;
}
})
if (isValid) {
$this.val('Edit');
tds.prop('contenteditable', false);
} else {
alert(errors);
}
}
});
// ----- Dialog Box -----
$( function() {
var dialog, form,
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
phoneRegex = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/,
mr_name = $( "#mr_name" ),
buyer_id = $( "#buyer_id" ),
poc_n = $( "#poc_n" ),
poc_e = $( "#poc_e" ),
poc_p = $( "#poc_p" ),
allFields = $( [] ).add( mr_name ).add( buyer_id ).add( poc_n ).add( poc_e ).add( poc_p ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
valid = valid && checkRegexp( mr_name, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid vendor name" );
valid = valid && checkRegexp( buyer_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Buyer ID" );
valid = valid && checkRegexp( poc_n, /^[a-zA-Z ]*$/, "Please enter a valid name" );
valid = valid && checkRegexp( poc_e, emailRegex, "Please enter a valid email" );
valid = valid && checkRegexp( poc_p, phoneRegex, "Please enter a valid phone number" );
if ( valid ) {
var $tr = $( "#html_master tbody tr" ).eq(0).clone();
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val() );
});
$tr.find('.mr_id').html( $( "#html_master tbody tr" ).length + 1 );
$( "#html_master tbody" ).append($tr);
/*
$( "#html_master tbody" ).append( "<tr>" +
"<td>" + mr_name.val() + "</td>" +
"<td>" + buyer_id.val() + "</td>" +
"<td>" + poc_n.val() + "</td>" +
"<td>" + poc_e.val() + "</td>" +
"<td>" + poc_p.val() + "</td>" +
"</tr>" );
*/
dialog.dialog( "close" );
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Row": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog( "open" );
});
} );
HTML/PHP code:
<?php
$host="xxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Stage_Rebate_Master ORDER BY MR_ID ASC";
?>
<html>
<body>
<div id="dialog-form" title="Add Vendor">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="mr_name">Vendor</label>
<input type="text" name="mr_name" id="mr_name" class="text ui-widget-content ui-corner-all">
<label for="buyer_id">Buyer ID</label>
<input type="text" name="buyer_id" id="buyer_id" class="text ui-widget-content ui-corner-all">
<label for="poc_n">POC Name</label>
<input type="text" name="poc_n" id="poc_n" class="text ui-widget-content ui-corner-all">
<label for="poc_p">POC Email</label>
<input type="text" name="poc_e" id="poc_e" class="text ui-widget-content ui-corner-all">
<label for="poc_p">POC Phone</label>
<input type="text" name="poc_p" id="poc_p" class="text ui-widget-content ui-corner-all">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>

Without Ajax - This can be done with a (PHP/ASP) 'pass-through' window.open - this is a window that you open which processes the passed parameters and writes them to an SQL database and then closes itself. This leaves the original site intact but updates the database with your changes.
So, window.open(saveChanges.php?param1=..&param2=..&etc,....)
The saveChanges.php file should read in the passed params and run the appropriate SQL to save updates.
Once completed, the saveChanges.php file should close itself with window.close()
Your database should now reflect the contents of your web page entries.

Related

C# Submitting http post request to fill a form

I am trying to submit a form using C# to my website. On my website I have a petition form where I have a few text boxes and a submit button, I can do this completely fine on the browser, but I want to do it from C#.
Here is the following javascript code it's very simple:
(function($) {
"use strict";
var $button = $('#sign-petition');
$button.submit(function(e){
e.preventDefault();
var $country = '';
var $state = '';
var $zip = '';
var $city = '';
var $terms = '';
var $newsletter = 0;
var $bio = '';
if( $( 'select[name="country"]', this ).length > 0 ) {
$country = $( 'select[name="country"]', this ).val();
}
if( $( 'input[name="state"]', this ).length > 0 ) {
$state = $( 'input[name="state"]', this ).val();
}
if( $( 'input[name="zip"]', this ).length > 0 ) {
$zip = $( 'input[name="zip"]', this ).val();
}
if( $( 'input[name="city"]', this ).length > 0 ) {
$city = $( 'input[name="city"]', this ).val();
}
if( $( 'input[name="terms"]', this ).length > 0 ) {
if( $( 'input[name="terms"]', this ).prop('checked') ){
$terms = $( 'input[name="terms"]', this ).val();
}
}
if( $( 'input[name="newsletter"]', this ).length > 0 ) {
if( $( 'input[name="newsletter"]', this ).prop('checked') ){
$newsletter = 1;
}
}
if( $( 'textarea.bio', this ).length > 0 ) {
$bio = $( 'textarea.bio', this ).val();
}
var data = {
'action': 'sign_petition',
'email' : $( 'input[name="email"]', this ).val(),
'fname' : $( 'input[name="fname"]', this ).val(),
'lname' : $( 'input[name="lname"]', this ).val(),
'bio' : $bio,
'signature' : $( '#signature', this ).val(),
'country' : $country,
'state' : $state,
'zip' : $zip,
'city' : $city,
'terms' : $terms,
'newsletter' : $newsletter
};
$.post( petition.ajaxurl, data, function( response ) {
//console.log(response);
response = JSON.parse(response);
if( typeof(response.errors) !== "undefined" && response.errors !== null ){
if( $( '#petition-errors' ).html() !== '' ){ $( '#petition-errors' ).html(''); }
$('#sign-petition .error').each(function (){
$(this).removeClass('error');
});
$.each( response.errors, function( key, error ){
$( '.' + key, '#sign-petition' ).addClass( 'error' );
$( '#petition-errors' ).append( '<li>' + error[0] + '</li>' );
});
} else{
$( '<p>' + response.success + '</p>' ).insertBefore( '#sign-petition' );
$('#sign-petition').hide();
}
});
});
})(jQuery);
I've used Microsoft's provided example and this is what i have so far, but it's not working.
string uriString = "https://example.org/";
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Create a new NameValueCollection instance to hold some custom parameters to be posted to the URL.
NameValueCollection myNameValueCollection = new NameValueCollection();
myNameValueCollection.Add("signature", "15c8c9a392");
myNameValueCollection.Add("email", "tom#appleseed.com");
myNameValueCollection.Add("fname", "Tom");
myNameValueCollection.Add("lname", "Appleseed");
myNameValueCollection.Add("country", "US");
myNameValueCollection.Add("state", "WA");
myNameValueCollection.Add("zip", "98174");
myNameValueCollection.Add("city", "Seattle");
var responseArray = myWebClient.UploadValues(uriString, myNameValueCollection);
var response = Encoding.ASCII.GetString(responseArray);
var outputFilePath = Environment.CurrentDirectory + "\\petition\\" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".html";
try
{
File.WriteAllText(outputFilePath, response);
}
catch (Exception e) { Console.WriteLine(e); }
Also here is the html code:
<form id="sign-petition" method="post">
<input type="hidden" id="signature" name="signature" value="15c8c9a392">
<input type="hidden" name="_wp_http_referer" value="/">
<div class="form-group">
<input type="text" class="form-control email" name="email" value="" placeholder="E-mail Address"">
</div>
<div class="form-group">
<input type="text" class="form-control fname" name="fname" value="" placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control lname" name="lname" value="" placeholder="Last Name">
</div>
<div class="form-group">
<select name="country" class="form-control" id="country">
<option value="0" selected="selected">Select a country ... </option>
<option value="US" label="United States">United States</option>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control lname" name="state" value="" placeholder="State / Province">
</div>
<div class="form-group">
<input type="text" class="form-control lname" name="zip" value="" placeholder="Zip / Postal Code">
</div>
<div class="form-group">
<input type="text" class="form-control lname" name="city" value="" placeholder="City">
</div>
<div class="form-group">
<textarea class="form-control bio" placeholder="comments" rows="3"></textarea>
</div>
<ul id="petition-errors"></ul>
<button type="submit" class="btn btn-primary">Sign Petition!</button>
</form>
Any help is appreciated
Thanks.
What about using an HttpClient and just posting the data? Something like this.
var data = new
{
action = "sign_petition",
signature = "15c8c9a392",
email = "tom.appleseed.com",
fname = "Tom",
lname = "Appleseed",
country = "US",
state = "WA",
zip = "98174",
city = "Seattle"
};
using (var client = new HttpClient())
{
var uriString = "https://example.org";
var result = client.PostAsync(uriString, new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")).Result;
if (!result.IsSuccessStatusCode)
{
//Handle the error
}
else
{
//Do something else
}
}

How to retrieve old text and subtract from total - JS

This is a follow up question on an existing question. I am able to get total sub-price tof products that i selected and add up to get the grand total. Now, when an item is deselected, i want to subtract the price of the item being deselected from the existing grand total?
How do i get that done please?
When i try to get the oldtext, it is always 0 .. why is this happening?
HTML
<div class="panel" id="panel">
<div>
<div >
<p> class="mygoods" >Total: <span ></span></p>
</div>
JS
<script type="text/javascript">
function order(food)
{
var ad = JSON.parse(food.dataset.food);
if(food.checked == true) {
$('.panel').append(
'<div class="container" style=" font-size:14px; "> '+
'<p class="total" ><span class="sub-total" name="total" id="total"></span></p>'+
'<input size="50" type="text" class="form-control quantity" id="qty" placeholder=" qty " name="quantity[]" required/>'+
'</div>'
)
}
else{
var total = $(".panel .container [data-id=" + ad.id + "]").parent().find(".total").text();
$(".panel .container [data-id=" + ad.id + "]").parent().remove();
if (total) {
$('.mygoods span').text(function(oldtext) {
console.log('this is my old text '+oldtext)
return oldtext ? oldtext - total : oldtext;
});
}
}
}
$('.panel').on('keyup','.quantity',function()
{
var sum;
container = $(this).closest('div');
quantity = Number($(this).val());
price = Number($(this).closest('div').find('.price').data('price'));
container.find(".total span").text(quantity * price);
sum = 0;
$(".sub-total").each(function(){
sum = sum + Number($(this).text());
})
$('.mygoods span').text(sum);
});
</script>
$( '.mygoods span' ).text( function( oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
the .text method returns the parameters index and text - you only are retrieving one. Therefore the index is being stored in the oldtext variable, not the text.
Type: Function( Integer index, String text ) => String A function
returning the text content to set. Receives the index position of the
element in the set and the old text value as arguments.
http://api.jquery.com/text/
You can fix this by simply adding another parameter.
$( '.mygoods span' ).text( function(index, oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
I tried copying a snippet over to show you, but the code you provided is not enough to build anything. The attempted build is below.
function order( food ) {
var ad = JSON.parse( food.dataset.food );
if ( food.checked == true ) {
$( '.panel' ).append( '<div class="container" style=" font-size:14px; "> ' +
'<p class="total" ><span class="sub-total" name="total" id="total"></span></p>' +
'<input size="50" type="text" class="form-control quantity" id="qty" placeholder=" qty " name="quantity[]" required/>' +
'</div>' )
} else {
var total = $( ".panel .container [data-id=" + ad.id + "]" ).parent().find(
".total" ).text();
$( ".panel .container [data-id=" + ad.id + "]" ).parent().remove();
if ( total ) {
$( '.mygoods span' ).text( function( index, oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
}
}
}
$( '.panel' ).on( 'keyup', '.quantity', function() {
var sum;
container = $( this ).closest( 'div' );
quantity = Number( $( this ).val() );
price = Number( $( this ).closest( 'div' ).find( '.price' ).data( 'price' ) );
container.find( ".total span" ).text( quantity * price );
sum = 0;
$( ".sub-total" ).each( function() {
sum = sum + Number( $( this ).text() );
} )
$( '.mygoods span' ).text( sum );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel" id="panel">
<div>
<div>
<p class="mygoods"> Total: <span></span></p>
</div>
</div>
</div>

javascript Alert to confirm if value entered twice

I have a form:
// 10 times
<input type="text" name="cityname" class="autocompletecity">
<input type="text" name="cityID" class="autocompletecityID">
When I enter the city name, it autocompletes the city name and the cityID from database with this code:
<?php for ($i = 0; $i < 10; $i++) { /*in the field class add $i */ ?>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 1 );
}
$( ".autocompletecity<?php echo $i ?>" ).autocomplete({
source: "/*path to json*/",
select: function( event, ui ) {
var item = ui.item;
if(item) {
$(".autocompletecityID<?php echo $i ?>").val(item.cityID);
$(this).val(item.value +' ' + item.country);
return false;
}
}
//code from J.D.
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index, element) {
var $element = $(element);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" +item.value + " " +item.country + "</a>" )
.appendTo( ul );
};
});
<?php } ?>
After it autocompletes the cityID, I would like to show an alert box if same cityID has alredy been entered: Click OK to confirm or Cancel to clear the cityname and cityID with repeated entry.
I tried to search in the jqueryui, but no luck...
Thanks!!
Try this:
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index) {
var $element = $(this);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}

Uncaught TypeError: undefined is not a function

I am newbie to js, I have copied a script from jqueryui.com for the dialog widget and pasted it in my Yii project, but I got an error: Uncaught TypeError: undefined is not a function, which is the function of $( "#dialog-form" ).dialog, so what is the error, and how I can fix it, here is the code:
$(function() {
var name = $( "#name" ),
email = $( "#email" ),
password = $( "#password" ),
allFields = $( [] ).add( name ).add( email ).add( password ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": function() {
var bValid = true;
allFields.removeClass( "ui-state-error" );
bValid = bValid && checkLength( name, "username", 3, 16 );
bValid = bValid && checkLength( email, "email", 6, 80 );
bValid = bValid && checkLength( password, "password", 5, 16 );
bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui#jquery.com" );
bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
if ( bValid ) {
$( "#users tbody" ).append( "<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>" );
$( this ).dialog( "close" );
}
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
$( "#create-user" )
.button()
.click(function() {
$( "#dialog-form" ).dialog( "open" );
});
});
Did you include something like
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
the problem is solved, its because I loaded a default jquery package instead of the customized Jquery package that contains the dialog widget.

Js/jQuery - How to hide/show an input created on the fly?

This code creates a group of elements (four inputs) on the fly. Once you create an element (four inputs) you can select/deselect, when you select an element will bring up the editor for the corresponding element. I've made a function to hide only the first element. The problem is that I can not make it comeback without affecting the other elements.
Instructions:
Click on the "Price" link, an element will be created on the fly (four nested inputs)
Select the element (four nested inputs) to bring up the editor ( one input and a brown little square).
Click on the little brown square to hide the first input of the element (four nested inputs) and that will hide the first input.
I need the little brown square to hide and show the same input.
Go here to see the full code:
To see the problem you have to create more than one element to find out.
http://jsfiddle.net/yjfGx/13/
This is the JS/jQuery code, for the full code go to the link above.
var _PriceID = 1;
$('#Price').on('click',function(){
var label = 'Price'
var Id = 'Price_';
var P = $( '<p class="inputContainer" />' ).fadeIn(100);
var l = $( '<label />' ).attr({'for':Id + _PriceID, 'id':Id + _PriceID, 'class':'priceLb'}).text( label ).after('<br/>');
var l1 = $( '<span class="dollar-sign" />' ).text( '$' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input1 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs',
'maxlength':'3', 'placeholder':'one',
'id':Id + _PriceID, 'class':'pricePh-1' })
.css({ "width":"60px", "paddingLeft":"1.3em", "paddingRight":"0.2em", "margin":"3px" });
var l2 = $( '<span class="priceComma-1" />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input2 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3',
'placeholder':'two', 'id':Id + _PriceID, 'class':'pricePh-2' })
.css({ "width":"68px", "paddingLeft":"0.7em", "paddingRight":"0.2em", "margin":"3px" });
var l3 = $( '<span class="priceComma-2" />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input3 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'3',
'placeholder':'three', 'id':Id + _PriceID, 'class':'pricePh-3' })
.css({ "width":"64px", "paddingLeft":"1em", "paddingRight":"0.2em", "margin":"3px" }); var l4 = $( '<span />' ).text( ',' ).css({"font-family":"Arial", "color":"#333", "font-weight":"bold"});
var input4 = $( '<input />' ).attr({ 'type':'text', 'name':'', 'class':'inputs', 'maxlength':'2',
'placeholder':'four', 'id':Id + _PriceID, 'class':'pricePh-4' })
.css({ "width":"37px", "paddingLeft":"0.5em", "paddingRight":"0.2em", "margin":"3px" });
P.append( l, l1, input1, l2, input2, l3, input3, l4, input4);
var D = $( 'form' );
P.on({
mouseenter: function() {
$(this).addClass("pb");
},
mouseleave: function() {
$(this).removeClass("pb");
}
});
P.appendTo(D);
_PriceID++;
});
/*** Select element individually and load editor. ***/
var flag = false;
$("form").on("click", "p", function () {
var cur = $(this).css("background-color");
if (cur == "rgb(255, 255, 255)") {
if (flag == false) {
$(this).css("background-color", "#FDD");
LoadPriceProperties($(this));
flag = true;
}
} else {
$(this).css("background-color", "white");
$('.properties-panel').hide();
flag = false;
}
});
/*** Element editor ***/
var LoadPriceProperties = function (obj) {
$('.properties-panel').css('display', 'none');
$('#priceProps-edt').css('display', 'block');
var label = $('.priceLb', obj);
var price1 = $('.pricePh-1', obj);
var price2 = $('.pricePh-2', obj);
$('#SetPricePlaceholder-1').val(price1.attr('placeholder'));
$('#SetPricePlaceholder-2').val(price2.attr('placeholder'));
/*** Getting an answer, depending on what they click on. ***/
$('#fieldOptionsContainer_1 div').bind('click', function () {
if ($(this).hasClass('field-option-delete')) {
RemoveUnwantedPriceField1($(this));
} else {
/*** Function loacated on "line 98" ***/
HideUnwantedPriceField_1($(this));
}
});
_CurrentElement = obj;
};
function HideUnwantedPriceField_1() {
var input = $('.pricePh-1', _CurrentElement);
var comma = $('.priceComma-1', _CurrentElement);
if($(input).is(":hidden")){
} else {
input.hide();
comma.hide();
}
}
Do you mean something like this: http://jsfiddle.net/Zaf8M/
var items=$('.m>li'), set= $('.set input'), num=0, item=$('.item'), list=$('.list');
item.hide();
items.click(function(){
$(this).addClass('sel').siblings().removeClass('sel');
num=$(this).index()+1;
set.prop( "disabled", false );
});
$('.close').click(function(){alert(3);});
$(window).click(function(e){
if( e.target.className=='sel' || e.target.type=='text'){return;}
else {
items.removeClass('sel'); set.prop( "disabled", true );
}
if(set.val()!='') {
item.clone().show()
.appendTo(list).children('.n').text(num)
.siblings('.p').text(set.val());
set.val('');
}
if( e.target.className=='close' ){$(e.target).parent().remove();};
});

Categories

Resources