Disable input after submit and count array element - javascript

function limitofTags(){
var tags = $('div').find('.tag').map(function(){
return $(this).text();
}).get();
var elem = [];
for (var i = 0; i < tags.length; ++i){
//store array elements
elem.push(tags[i]);
if(elem.length < 2){
$("#tags").prop('disabled',false);
}
else{
$("#tags").prop('disabled',true);
}
}
}
As for html, it is small div with button. When I type tags in input textfield, it will be appended to div area. When tags are more than 2, input textfield will be disabled to prevent more tags from being added. After submit the form, div showed the same number of tags but input textfield won't stay disabled. So how to make input textfield stay disabled if tags are more than 2 in div?
Appreciate the insight or help. I have been searching for online answers but seem not to find what I need the input text disable after submit.

You should probably check the length after the array is populated, and you're creating an elem array that is exactly the same as the tags array you have :
function limitofTags(){
var tags = $('div').find('.tag').map(function(){
return $(this).text();
}).get();
$("#tags").prop('disabled', tags.length >= 2);
}

Related

Get content of div including input values

I'm replacing some specific character by inputs via regexp.
Div looks like that:
1) <div>Text text text text <input> text text <input> text</div>
2) <div>text Text <input> text <input> text text Text</div>
Is it possible to get whole text including input values from a div (with id 'body' in my case)?
jQuery code:
var body = data.body.replace(/\.\.\./g, "<input class='bodyy' type='text' size='2' />");
$("#body").html(body);
Fiddle: https://jsfiddle.net/uepf87fc/
You can parse it yourself with a function, here's an example:
function getTextWithInputValues(id) {
var element = document.getElementById(id);
if (!element) {
return null;
}
var elementText = element.innerHTML; // Get the entire text from your element
var elementInputs = element.getElementsByTagName('input'); // fetch all inputs from your element
// replace all input fields with their respective values
Object.getOwnPropertyNames(elementInputs).forEach(
(input) => {
var inputText = elementInputs[input].outerHTML;
if (elementText.search(inputText) > 0) {
elementText = elementText.replace(inputText, elementInputs[input].value);
}
}
);
return elementText;
}
You can test it right here by opening a console, paste this code in, then type in something in the search box on the top of the page (don't click search, just type in something), then when you call the function in the console like getTextWithInputValues('search') it will output something like
<svg ......</svg>
your-text-here
<button .....</button>
Hope this helps.
Even though you asked for REGEX, I don't believe it is by any means needed.
This will return the data in an array. With the first index being the body text, and each input field value thereafter.
var values = [];
values.push($('#body').text());
var inputs = $('#body input');
for(var i = 0; i < $(inputs).length; i++)
{
var currentElement = $(inputs)[i];
values.push($(currentElement).val());
}
console.log(values);

Error message not showing and hiding depending on if else statement

I have a function that loops through all of the inputs of my form and checks if they are filled or not. If the field is blank, it makes that specific input pink and returns false.
I'm trying to add a "Field Required" message underneath the inputs that are not filled. So i coded an extra table row after each one, with a div that holds the error message. The css for the div is set to "display:none" on page load.
Right now my function is showing "required" for every input and not just the ones that are blank, but the pink coloring is still working correctly.
How do I get the "required" div to show and hide correctly like the pink coloring does?
checkinputs = function (blockOne,blockTwo) {
inputGood = true;
blOne = $(blockOne);
blTwo = $(blockTwo);
blInput = [blOne,blTwo];
for (x = 0; x < 2; x++) {
var validators = blInput[x].find(" [id$='RequiredIndicator']").parent().parent('tr').find(':input:not(:hidden)');
var notAllFilled = validators.filter(function(){
var myInput = $(this); //.parent().parent('tr').find(':input');
var filledVal = myInput.val();
var isFilled = $.trim(filledVal).length;
if (isFilled) {
$(this).css('background-color', 'white');
$(this).closest('div').find('.required').hide();
$(this).parent('td').prev('td').find('span').text('*');
}
else {
$(this).css('background-color', 'pink');
$(this).closest('div').find('.required').show();
$(this).parent('td').prev('td').find('span').text('*');
inputGood = false;
}
return isFilled;
}).length;
var inputCount = validators.length;
};
if( !inputGood ){
$('#errorAlert').append('<span style="font-weight:bold;">"Some required information is missing. Please complete the missing fields below."</span>' + '<br><br>');
$('#errorAlertTwo').append('<span style="font-weight:bold;">"Some required credit card information is missing. Please complete the missing fields below."</span>' + '<br><br>');
}
return inputGood;
};
HERE IS A FIDDLE OF THE ISSUE:
http://jsfiddle.net/RNMM7/
Your issue is almost definitely your line to show the div:
$(this).closest('div').find('.required').show();
What this line does is:
Starting at your $(this), it finds the nearest ancestor [including $(this)] that is a div, going up the DOM tree
Finds all elements with class 'required' under that div, and shows them.
Without seeing how your HTML is structured, my guess is that the nearest div element up the DOM tree encompasses all your .required elements. You'd need to replace the 'div' in that statement with an element lower in the DOM tree that would only encompass your $(this) and the one .required element you want to show.

changing text for a selected option only when its in selected mode

I am not sure if I confused everyone with the above title. My problem is as follows.
I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.
Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.
I am able to do this by calling
this.options[this.selectedIndex].text = "changed text";
in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.
I am stumped! is there a simpler way to do this?
Any help would be great.
Thanks
You can store previous text value in some data attribute and use it to reset text back when necessary:
document.getElementById('test').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text = "changed text";
// Reset texts for all other options but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};
http://jsfiddle.net/kb7CW/
You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/
Here is the script for it also:
//check if the changed text option exists, if so, hide it
$("select").on('click', function(){
if($('option#changed').length > 0)
{
$("#changed").hide()
}
});
//bind on change
$("select").on('change', function(){
var val = $(":selected").val(); //get the value of the selected item
var text = $(':selected').html(); //get the text inside the option tag
$(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
$(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
else
$('#changed').val(val) //if it already exists, change its value
$(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;
});

Limit the number of children in a form using Javascript

I am trying to limit the number of additional form input fields that a user can add dynamically to a file upload form to just 3. The form is loaded with one static input field and through javascript can add additional fields with an add button or remove additional form input fields with a remove button. Below is the html in it's static form.
<fieldset>
<legend>Upload your images</legend>
<ol id="add_images">
<li>
<input type="file" class="input" name="files[]" />
</li>
</ol>
<input type="button" name="addFile" id="addFile" value="Add Another Image" onclick="window.addFile(this);"/>
</fieldset>
With javascript I would like to create a function where the number of child elements are counted and if the number is equal to three then the "Add Another Image" button becomes disabled. In addition, if there are three elements in the form the user - with the remove button - removes a child then the "Add Another Image" button becomes enabled again.
I think I'm may be missing some crucial lines of code. The below javascript code only allows me to add one additional input field before the Add Another Image button becomes disabled. Removing this field with the remove file button removes the field but the Add Another Image button is still disabled. Below is where I'm currently at with the javascript.
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
}
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = nodelist.length;
for(i = 0; i < count; i++) {
if (nodelist[i] ==3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
}
}
Oh, OK, I've tested out the code now and see a couple of problems:
You're counting the number of child elements but this includes the text elements so there's actually one for the <li> and one for the text within it.
You've enclosed the true/false setting for the disabled property in quotes but it doesn't work and always set's it to false.
The remove button doesn't re-enable the add button.
I found this to work:
function addFile(addFileButton) {
var form = document.getElementById('add_images');
var li = form.appendChild(document.createElement("li"));
//add additional input fields should the user want to upload additional images.
var f = li.appendChild(document.createElement("input"));
f.className="input";
f.type="file";
f.name="files[]";
//add a remove field button should the user want to remove a file
var rb = li.appendChild(document.createElement("input"));
rb.type="button";
rb.value="Remove File";
rb.onclick = function () {
form.removeChild(this.parentNode);
toggleButton();
}
toggleButton();
}
function toggleButton() {
var form = document.getElementById('add_images');
//create the option to dispable the addFileButton if the child nodes total "3"
var nodelist;
var count;
nodelist = form.childNodes;
count = 0;
for(i = 0; i < nodelist.length; i++) {
if(nodelist[i].nodeType == 1) {
count++;
}
}
if (count >= 3) {
document.getElementById("addFile").disabled = true;
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = false;
}
}
I would suggest a slightly different approach. Create all three file input fields statically and provide a clear button. If the user chooses to leave it empty they can. If that is not elegant use your "Remove" to simply hide the field (CSS style display: none;).
I'm not sure why you're using the for loop? Shouldn't it be like this:
var nodelist = form.childNodes;
if (nodelist.length >= 3) {
document.getElementById("addFile").disabled = 'true';
}
else { //if there are less than three keep the button enabled
document.getElementById("addFile").disabled = 'false';
}
The last part of that function is a bit strange. Technically, when adding fields, you should only be disabling the button (i.e. you could never enable the button by adding fields). I would suggest removing the for loop and going with:
var count = form.getElementsByTagName("li").length;
if(count == 3)
document.getElementById("addFile").disabled = true;
The reason the add field button is still disabled when you remove an item is because you don't re-enable the add field button when you click remove. Try this for the remove button click handler:
rb.onclick = function () {
form.removeChild(this.parentNode);
document.getElementById("addFile").disabled = false;
}

how to find out how many items are selected in select box

I have a select box which has more than 200 items.
Below the select box is the submit button which submits the form using javascript.
I want to restrict the user to only select 100 items from the select box. If they select box and try to submit the form then it will say Select 100 Only
How can I do this in Javascript?
You can either:
Loop through all of the options elements and check the selected attribute:
var cnt = 0;
for (var i = 0; i < selectbox.options.length; i++) {
if (selectbox.options[i].selected === true) {
cnt++;
}
}
return cnt;
Or you can get the value of the select element and split the value by comma and base it on the number of items in the array.
var vlu = selectbox.value;
var vlus = vlu.split(',');
return vlus.length;

Categories