Add/Remove value to input on click - javascript

i have this code that i use, and on click i put email in field, but what i want to accomplish is that on next click on same field it removes email if one already exist in input.
Here is my code:
<p class="email">mail1#gmail.com</p>
<p class="email">something#gmail.com</p>
<p class="email">third#gmail.com</p>
<input type="text" id="contact-email" value="" class="form-control" style="width:500px" />
And js:
var $contact = $('#contact-email');
$('.email').on('click', function () {
if ($contact.val()) {
$contact.val($contact.val() +'; '+ $(this).text());
} else {
$contact.val($(this).text());
}
});
and fiddle https://jsfiddle.net/2dffwew5/2/

I would store selected email addresses to an array. Then push or splice the clicked email.
var $contact = $('#contact-email');
var emails = [];
$('.email').on('click', function () {
var index = emails.indexOf($(this).text());
if (index > -1) {
emails.splice(index, 1);
} else {
emails.push($(this).text());
}
$contact.val(emails.join(";"));
});
https://jsfiddle.net/jdgiotta/ze7zebzq/

I would suggest that you add a check to see if the current text contains the selected email address. If it does, then remove it. Otherwise add it.
You will also need to cater for leading/trailing dividers, which can easily be done with a couple of conditional checks.
Something like this:
var $contact = $('#contact-email');
$('.email').on('click', function () {
var text = $(this).text(); // Get the value to insert/remove.
var current = $contact.val(); // Get the current data.
// Check if the value already exists with leading seperator, if so remove it.
if (current.indexOf('; ' + text) > -1) {
$contact.val(current.replace('; ' + text, ''));
}
// Check if the value already exists with trainling seperator, if so remove it.
else if (current.indexOf(text + '; ') > -1) {
$contact.val(current.replace(text + '; ', ''));
}
// Check if the value already exists with no seperator (on it's own), if so remove it.
else if (current.indexOf(text) > -1) {
$contact.val(current.replace(text, ''));
}
// Otheriwse, it doesn't exist so add it.
else {
if (current) {
$contact.val(current + '; ' + text);
} else {
$contact.val(text);
}
}
});
Here is a working example

Related

variables in loop for cycle with javascript

I simplify my problem to a minimum because in reality my code is very long and complex to explain.
I have two text input fields, in the first field I can insert a series of values, while the second field receives the values of the first field and compares them with those it already has. if there are double values the function warns and the user can choose whether to overwrite them or delete them, otherwise the value is added.
I want to do this through a for loop.
function prova() {
var stringa_valoredainserire = document.getElementById("valoredainserire").value;
var stringa_valoredacambiare = document.getElementById("valoredacambiare").value;
var stringa_valoredacambiare2 = document.getElementById("valoredacambiare");
mioarray = stringa_valoredainserire.split("; ");
var i, len, text;
//inizio ciclo for
for (i = 0, len = mioarray.length, text = ""; i < len; i++) {
if (stringa_valoredacambiare.indexOf(mioarray[i]) !== -1) {
if (confirm('il valore ' + mioarray[i] + ' esiste, ok per sovrascriverlo, annulla per cancellarlo')) {
stringa_valoredacambiare2.value = stringa_valoredacambiare.replace(mioarray[i], mioarray[i]);
} else {
stringa_valoredacambiare2.value = stringa_valoredacambiare.replace(mioarray[i] + '; ', '');
}
} else {
stringa_valoredacambiare2.value = stringa_valoredacambiare2.value + mioarray[i] + '; ';
}
}
}
<input id="valoredainserire" value="" type="text">
<input id="valoredacambiare" value="pere; cipolle; mele; " type="text" readonly>
<input type="button" onclick="prova();" value="Prova">
the problem is that if the values to be entered in the first input field are equal to the values of the second, if I wanted to delete them, the function only deletes the last one, because it is the last variable that keeps it in memory.
how can I remedy this situation? some idea? Thanks in advance.

javascript function to prevent user from changing the value of a specific column

Hope you're doing well
I'm new to JavaScript and I need your help to complete the code below.
I've written a JS code as you can see below :
$("#input_KindCode").change(function () {
if ($(this).val() == 1) {
RunSql("Select DateKey From ProjectExecution.Contractinfo WHERE PlanCode = " + $("#input_PlanCode").val() + " AND ProjectCode = '" + $("#input_ProjectCode").val() + "' AND ContractCode = '" + $("#input_ContractCode").val() + "' AND KindCode = 1 ", function (data) {
if (data.length > 0) {
$("#input_DateKey").val(data[0].DateKey);
/////// THIS PART///////
} else {
$("#input_DateKey").val('');
EnableCol("DateKey");
}
});
}
else {
$("#input_DateKey")[0].value = '';
EnableCol("DateKey");
};});
In the 'RunSql' part of the code , I'm checking whether the 'datekey' column has value if true the value will show up in the field otherwise the user must enter the value for the column.
The problem is I want to add something to the code . I want to show the value if it exists AND I want to disable the column so that the user can not change the value . I can not use the function 'disable column' cause it does not work in my case are there any other functions ??
so I want a function to prevent user from changing the value of the column if it is being shown on the field. the function must be written in the 'This part' part of the code
Thanks in advance
You can disable this input field using jquery. To perform this you need to add one line.
Code:
if (data.length > 0) {
$("#input_DateKey").val(data[0].DateKey);
$("#input_DateKey").prop('disabled',true);
} else {
$("#input_DateKey").val('');
$("#input_DateKey").prop('disabled',false);
EnableCol("DateKey");
}

How do i rearrange the number in java script loop?

I have done the dynamic generates textbox based on the number that user type. For example, user types 10 in the input box clicked add will generate 10 input box. I have a label to catch the number.
here is my question
how do I start from 1?
how do I rearrange the number when user remove one of the input boxes
here is my javascript
$(document).ready(function () {
$("#payment_term").change(function () {
var count = $("#holder input").size();
var requested = parseInt($("#payment_term").val(), 10);
if (requested > count) {
for (i = count; i < requested; i++) {
$("#payment_term_area").append('<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label>' + i + 'Payment</label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
$("#payment_term_area").on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
calculateTotal();
x--;
})
}
});
});
here is my view
<input type="text" id="payment_term" />
<button onclick="function()">Add</button>
<div id="payment_term_area"></div>
You were nearly there, however, by hardcoding the label's you were making updating them difficult for yourself. I have created a jsfiddle of my solution to your problems. I personally prefer to cache the values of my jQuery objects so that they arent hitting the DOM each time they are referenced, for the performance boost (hence why they are listed at the top). I also, find it nicer to bind the click event in JS rather than using the html attribute onclick, but this is just a preference.
JSFIDDLE
Javascript
// create cache of jQuery objects
var add_payment_terms_button = $('#add_payment_terms');
var payment_term_input = $('#payment_term');
var payment_term_area = $('#payment_term_area');
var default_payment_values = ['first value', 'second value', 'third value', 'forth value', 'fifth value'];
var default_other_value = 'default value';
// bind to generate button
add_payment_terms_button.on('click', generatePaymentTerms);
function generatePaymentTerms(){
var requested = parseInt(payment_term_input.val(), 10);
// start i at 1 so that our label text starts at 1
for (i = 1; i <= requested; i++) {
// use data-text to hold the appended text to the label index
payment_term_area.append(
'<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label data-text=" Payment"></label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
// call the function to set the labels
updateProductIndexes();
}
function updateProductIndexes(){
// get all labels inside the payment_term_area
var paymentLabels = payment_term_area.find('.product_wrapper label');
for(var x = 0, len = paymentLabels.length; x < len; x++){
// create jQuery object of labels
var label = $(paymentLabels[x]);
// set label text based upon found index + 1 and label data text
label.text( getOrdinal(x + 1) + label.data('text'));
// either set the next input's value to its corresponding default value (will override set values by the user)
label.next('input.payment_term').val(default_payment_values[x] || default_other_value)
// or optionally, if value is not equal to blank or a default value, do not override (will persist user values)
/* var nextInput = label.next('input.payment_term');
var nextInputValue = nextInput.val();
if(nextInputValue === '' || default_payment_values.indexOf(nextInputValue) >= 0 || nextInputValue === default_other_value){
nextInput.val(default_payment_values[x] || default_other_value)
} */
}
}
// courtesy of https://gist.github.com/jlbruno/1535691
var getOrdinal = function(number) {
var ordinals = ["th","st","nd","rd"],
value = number % 100;
return number + ( ordinals[(value-20) % 10] || ordinals[value] || ordinals[0] );
}
payment_term_area.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
// after we remove an item, update the labels
updateProductIndexes();
})
HTML
<input type="text" id="payment_term" />
<button id="add_payment_terms">Add</button>
<div id="payment_term_area"></div>
First you have to give id for each label tag ex:<label id='i'>
Then you can re-arrange the number by using document.getElementById('i')
Refer the Change label text using Javascript
hope this will be much helpful

fill the input type hidden from selected multiple option on jquery

I have a input that have type like this:
<input class="emailSend" name="emailSend" type="hidden">
Then I have a multiple select option like this
<div class="controls">
<select id="email" multiple data-rel="chosen" class="input-xlarge" name="email[]">
<?php
foreach ($atasan as $data) {
echo "<option value='" . $data['email'] . "'>" . $data['email'] . "</option>";
}
?>
</select>
</div>
My problem is, I want to fill that hidden input from the option that selected from multiple select option. So let say, the selected option is 'email1', 'email2', 'email3' then would be affected to hidden type like this 'email1, email2, email3'.
I have try this for 3 hour in jquery and I am stuck. My code is like this.
$("#email").change(function() {
var elements = $("#email option:selected").length;
var input = $(".emailSend");
$(".emailSend").html("");
$.each($("#email option:selected"), function(/*index, element*/) {
input.val(input.val() + $(this).html() + ", ");
if (index < elements - 1) {
//code to remove last comma
//any idea ?
}
});
});
So appreciated for the help...
EDIT Here is the fiddle :JSFIDDLE
Updated FIDDLE now that I see what you meant by looking at the fiddle you made.
this is actually all you need to do...
Updated to include spaces between the addresses!
$("#email").on('change', function() {
var thisval = $(this).val() + '';
var myarr = thisval.split(',');
var newval = '';
myarr.forEach(function(i,v) {
newval += i + ' , ';
});
newval = newval.slice(0, newval.length - 3);
$("#emailsend").val(newval);
});
Commented Version (for learning and stuff)
$("#email").on('change', function() {
//the extra space at the end is to typecast to string
var thisval = $(this).val() + '';
//takes string of comma separated values and puts them
//into an array
var myarr = thisval.split(',');
//Initialize a new string variable and loop through
//the array we just created with MDN's forEach()
var newval = '';
myarr.forEach(function(i,v) {
//add to the string through each iteration,
//including comma with spaces
newval += i + ' , ';
});
//use .slice() to trim three characters off the
//end of the final string. (strip final comma)
newval = newval.slice(0, newval.length - 3);
//and last but not least, assign our newly created
//and properly formatted string to our input element.
$("#emailsend").val(newval);
});

reset values of not selected fields of dropdown

I have a dropbox that when selected it displays its respective fields
in first image you can see there is A person without an ID so when selected it displays
something like:
if you see I added 12
Now if i change my mind and select the other option (person with ID) one field is displayed like:
I added 9999
That is ok, but now if I change my mind again and return to other selected option the values are still there like:
I would like to clean them... How can I accomplish that?
It does not matter to fill all respective fields again, I want to reset values in that case if select
person without ID, delete the 9999, on the other hand, if i select person with Id, i want to reset the vakue 12
please take a look at my fiddle
some of the jquery code is:
//function available
function validate(id, msg) {
var obj = $('#' + id);
if(obj.val() == '0' || obj.val() == ''){
$("#" + id + "_field_box .form-error").html(msg)
return true;
}
return false;
}
$(function () {
$('#has_id').show();
$('#select_person').change(function () {
$('.persons').hide();
if ($('#select_person').val() == 'typeA') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type A--').appendTo("#has_id");
$("<option/>").val('person-A-withID').text('person-A-withID').appendTo("#has_id");
$("<option/>").val('person-A-withoutID').text('person-A-withoutID').appendTo("#has_id");
}
if ($('#select_person').val() == 'typeB') {
$("#has_id").html('');
$("<option/>").val('0').text('--Choose Type B--').appendTo("#has_id");
$("<option/>").val('person-B-withID').text('person-B-withID').appendTo("#has_id");
$("<option/>").val('person-B-withoutID').text('person-B-withoutID').appendTo("#has_id");
}
});
$('#has_id').change(function () {
$('.persons').hide();
$('#' + $(this).val()).show();
});
});
var validation = function(){
var err = 0;
err += validate('select_person', "select person.");
err += validate('has_id', "Select whether it has an ID or not.");
if(err == 0){
alert('continue');
}else{
alert('error');
}
};
Simply make this change:
$('#has_id').change(function () {
$('.persons input').val('');
$('.persons').hide();
$('#' + $(this).val()).show();
});
New fiddle: http://jsfiddle.net/6m27M/
This simply clears out all the values any time a change is made to the #has_id dropdown.

Categories

Resources