I've got a number of input id's in a form as follows (example, not complete form) This is for a Chrome Extension so I cannot modify the form.
<form>
<input id="data-draft-brand-name" />
<input id="data-draft-name-en-us" />
<input id="data-draft-bullet-points-bullet1-en-us" />
<input id="data-draft-bullet-points-bullet2-en-us" />
<input id="data-draft-description-en-us" />
</form>
What I am doing is using keyup on each on the inputs, and then doing the same thing for each id like so:
$( "#data-draft-description-en-us" ).keyup(function() {
var currentVal = $(this).val();
currentVal = currentVal.toLowerCase();
var currentLength = currentVal.length;
currentLength = 2000 - currentLength;
$('#description-count').text(`${currentLength} characters left`);
if(currentVal.indexOf('word') !== -1) {
$('#data-draft-description-en-us').css('border','1px solid red');
$('#data-draft-description-en-us').css('background','red');
} else {
$('#data-draft-description-en-us').css('border','1px solid #a6a6a6');
$('#data-draft-description-en-us').css('background','none');
}
});
As you can see, there will be a lot of repetition. Is there anyway I can pass an array of id's to keyup, and then access the id in the function. Some pseudo code as an example..
$(["#data-draft-brand-name","#data-draft-name-en-us"]).keyup(function(inputID) {
$(inputID).css('border','1px solid red');
}
Here you go with a solution
$("#data-draft-brand-name, #data-draft-name-en-us").keyup(function() {
var id = $(this).attr('id');
$('#' + id).css('border','1px solid red');
});
No need to provide square brackets [], id should be separated by comma.
Here you go with jsfiddle https://jsfiddle.net/tjkah0ck/2/
$( "#data-draft-brand-name, #data-draft-name-en-us" ).keyup(function() {
var currentVal = $(this).val();
currentVal = currentVal.toLowerCase();
console.log(currentVal);
var currentLength = currentVal.length;
currentLength = 2000 - currentLength;
$('#description-count').text(`${currentLength} characters left`);
if(currentVal.indexOf('word') !== -1) {
$('#data-draft-description-en-us').css('border','1px solid red');
$('#data-draft-description-en-us').css('background','red');
} else {
$('#data-draft-description-en-us').css('border','1px solid #a6a6a6');
$('#data-draft-description-en-us').css('background','none');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="data-draft-brand-name"/>
<input id="data-draft-name-en-us"/>
<input id="data-draft-bullet-points-bullet1-en-us" />
<input id="data-draft-bullet-points-bullet2-en-us" />
<input id="data-draft-description-en-us" />
</form>
Hope this will help you.
You can use start with selector for attribute, [name^=”value”] [https://api.jquery.com/attribute-starts-with-selector/][1]
If we need to edit your code then it should be below
$( "div[id^='data-draft-'" ).keyup(function() {
var currentInput = $(this);
var currentVal = $(this).val();
currentVal = currentVal.toLowerCase();
console.log(currentVal);
var currentLength = currentVal.length;
currentLength = 2000 - currentLength;
$('#description-count').text(`${currentLength} characters left`);
if(currentVal.indexOf('word') !== -1) {
currentInput.css('border','1px solid red');
currentInput.css('background','red');
} else {
currentInput.css('border','1px solid #a6a6a6');
currentInput.css('background','none');
}
});
Enjoy
To realize what you want, you should use a class to define which input will have a keyup event handler.
Also, you can retreive the id of the current input by calling attr("id").
So you'll have a code like this:
$(document).ready(function(){
$(".keupinput").keyup(function(event) {
var inputid = $(this).attr("id");
console.log("I'm the " + inputid + " input.");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="keupinput" id="data-draft-brand-name" />
<input class="keupinput" id="data-draft-name-en-us" />
<input class="keupinput" id="data-draft-bullet-points-bullet1-en-us" />
<input class="keupinput" id="data-draft-bullet-points-bullet2-en-us" />
<input class="keupinput" id="data-draft-description-en-us" />
</form>
Related
In my script, I have input fields which are added dynamically. I have to get all input values using php but the problem in that $_POST['poids'] give me just the first value of input array, so just the first element of the array poids. This is my code:
$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]", $wrapper).map(function() {
return +this.value
}).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item", $wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
var err_msg = 'limit riched';
//alert(err_msg);
window.alert(err_msg);
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<div class="container1" style="min-height:200px">
<button class="add_form_field">Add New Field ✚</button>
<form method="post" action="postForm.php">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
Delete
</div>
<button type="submit" name="" class="btn btn-danger btn-responsive "> Send </button></center>
</a>
</form>
</div>
to get post (postForm.php):
$poids = $_POST['poids'];
foreach($poids as $poid) {
echo " -->" .$poid;
}
I hope that you undestand what I mean.
Thank you in advance
The problem is that you're appending the div with the new input fields to $wrapper, but that's outside the form. You need to put it inside the form.
Change
$wrapper.append($form_colis); //add input box
to
$('.item', $wrapper).last().after($form_colis); //add input box
I'm no PHP expert, but by just browsing the code provided, it seems you're just searching for inputs with a name value of poids.
const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()
Then when you create a bew input, you do not append poids to the input name.
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis);
Therefore, you will only find one with your method, and that's this one:
<input type="text" placeholder="Poids" name="poids[]">
So to solve this, inside the $form_colis method, add poids to it I do believe.
I have an input where I want the first character to be #.
That means if the user writes something, it automatically adds the #, or better, the # is already present in the input.
How do I do that? I thought i could do that with jQuery mask but I couldn't make it work.
Here is the code,
$("#your-input-id").keypress(function(e) {
if (e.keyCode != 8) {
var text = this.value;
if (text.length == 0) {
this.value = text + '#';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form action="#">
<input id="your-input-id" type="text" placeholder="Type a text here..." data-prefix="#" />
</form>
Hope this will work.
This will append # when you will start typing, and it will append everything later to #.
EDIT
$("#your-input-value").keydown(function(e) {
var cur_val=$(this).val();
var field=this;
setTimeout(function () {
if(field.value.indexOf('#') !== 0) {
$(field).val(cur_val);
}
}, 1);
});
See this solution http://codepen.io/bachors/pen/yeJOrg
Running example to meet your needs:
/***********************************************
* #### jQuery Prefix Input ####
* Coded by Ican Bachors 2015.
* http://ibacor.com/labs/jquery-prefix-input/
* Updates will be posted to this site.
***********************************************/
$(".yourClass").focus(function(){var a=$(this).data("prefix"),ibacor_currentId=$(this).attr('id'),ibacor_val=$(this).val();if(ibacor_val==''){$(this).val(a)}ibacor_fi(a.replace('ibacorat',''),ibacor_currentId);return false});function ibacor_fi(d,e){$('#'+e).keydown(function(c){setTimeout(function(){var a=bcr_riplis($('#'+e).val()),qq=bcr_riplis(d),ibacor_jumlah=qq.length,ibacor_cek=a.substring(0,ibacor_jumlah);if(a.match(new RegExp(qq))&&ibacor_cek==qq){$('#'+e).val(bcr_unriplis(a))}else{if(c.key=='Control'||c.key=='Backspace'||c.key=='Del'){$('#'+e).val(bcr_unriplis(qq))}else{var b=bcr_unriplis(qq)+c.key;$('#'+e).val(b.replace("undefined",""))}}},50)})}function bcr_riplis(a){var f=['+','$','^','*','?'];var r=['ibacorat','ibacordolar','ibacorhalis','ibacorkali','ibacortanya'];$.each(f,function(i,v){a=a.replace(f[i],r[i])});return a}function bcr_unriplis(a){var f=['+','$','^','*','?'];var r=['ibacorat','ibacordolar','ibacorhalis','ibacorkali','ibacortanya'];$.each(f,function(i,v){a=a.replace(r[i],f[i])});return a}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form action="#">
<input id="yourInput" class="yourClass" type="text" placeholder="Type a text here..." data-prefix="#" />
</form>
You can try this,
HTML
<input type="text" class="txtUrl" />
Javascript
$('.txtContent').keydown(function(e) {
var cur_val = $(this).val();
if(cur_val.length == 0) {
$(this).val('#' + cur_val);
}
});
Here is the working fiddle: http://jsfiddle.net/jMH9b/43/
Hope this helps!
As you stated, if there is already a SLASH it should not do anything. Here is the solution
$('#description').bind('input', function(event){
var currentVal = $(this).val();
$(this).val(currentVal.indexOf('#') !== 0 ? ('#' + currentVal) : currentVal)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label name="description">Enter some text</label>
<input type="text" id="description" name="description">
<input id='e' onKeyup='test(this)' value='#'/>
var input = document.getElementById('e');
function test(e){
input.value = e.value.charAt(0) !== '#' ? input.value = '#' + e.value : e.value
}
hope this helps...
I am trying to find the empty input types like textbox, select and li elements inside a jQuery resultset.
My resultset is (requiredfields) -
$requiredFields = $(".f-form-required.f-form-field").filter(function(){
if($(':input:not([type="hidden"])'))
return $(this);
});
And on that resultset I want to query for empty inputs like textbox, select and li elements. But it seems I am doing something wrong. Can someone suggest me how to do that.
Currently I am doing this to get empty textboxes but not working -
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (this.val == "") {
emptyInputs = emptyInputs + 1;
}
});
});
I am trying to do same for finding out empty dropdown/select elements and list / li elements over $requiredFields collection.
There is no val property. Try using .val() instead or this.value:
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (jQuery(this).val() == "") {
emptyInputs = emptyInputs + 1;
}
});
});
or:
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (this.value == "") {
emptyInputs = emptyInputs + 1;
}
});
});
I think you arn't using .filter() quite as it is expected to be used. Consider something like this:
<html>
<body>
<div>
<input type="text" id="text1" class="f-form-required f-form-field" />
<input type="text" id="text2" class="f-form-required f-form-field" value="test" />
<input type="text" id="text3" class="f-form-required f-form-field" />
</div>
</body>
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function test(){
var $requiredFields = $('.f-form-required.f-form-field');
var $errorFields = $requiredFields.filter(function () {
var $this = $(this);
return $this.is('input') && $this.val() === '';
});
var errorCount = $errorFields.length;
console.log('errors:' + errorCount);
}
$(document).ready(function(){
test();
}
</script>
Is it possible to write a Javascript function to delete form a field when somebody does not fill in the field?
<form id="myform">
<label for="q1" id="q1label">question 1</label>
<input type="text" id="q1" name="q1"/>
<label for="q2" id="q2label">question 2</label>
<input type="text" id="q2" name="q2"/>
<label for="q3" id="q3label">question 3</label>
<input type="text" id="q3" name="q3"/>
<input type="submit" value="Delete blank fields" onclick="return checkanddelete"/>
</form>
If somebody does not fill in question 2 for example, it deletes question 2 label and the field.
For jQuery:
<script type="text/javascript">
function checkanddelete() {
$('input').each(function(){
if ($(this).val() == '') {
var id = $(this).attr('id');
$.remove('#' + id);
$.remove('#' + id + 'label');
}
});
}
</script>
For JavaScript:
<script type="text/javascript">
function checkanddelete() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++)
{
if (document.getElementsByTagName("input")[i].value.length == 0) {
var id = document.getElementsByTagName("input")[i].id;
(elem=document.getElementById(id)).parentNode.removeChild(elem);
(elem=document.getElementById(id + 'label')).parentNode.removeChild(elem)
}
}
}
</script>
Something like this?
With jquery:
$("#myform :text").each(function(){
if( !$.trim($(this).val()) )
$(this).prev('label').andSelf().remove();
});
i am using folloing function to remove element from document.
function removeElement(id)
{
if(typeof id === "object")
return id.parentNode.removeChild(id);
else
return (elem=document.getElementById(id)).parentNode.removeChild(elem);
}
You can pass a dom element or element Id itself to delete .
The following should do what you want :
var inputToDelete = document.getElementById("q2");
if (inputToDelete.value == "") {
var labelToDelete = document.getElementById("q2label");
var parentNode = document.getElementById("myform");
parentNode.removeChild(labelToDelete);
parentNode.removeChild(inputToDelete);
}
I'm trynig to come up with a clean and efficient way of handling form input names when dynamically adding more to the POST array.
For example, if I have the following form:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I then click an 'addmore' button which duplicates that HTML and adds it back into the document. Resulting in:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I'm trying to find the best way to increment that name index so I can use the data on the server. So far, I've been using the following code:
$('.addmore').click(function()
{
var $button = $(this);
var $fieldset = $button.prev('fieldset');
var $newset = $('<div class="new">' + $fieldset[0].innerHTML + '</div>');
$newset.insertBefore($button);
updatenames($newset, $('fieldset').length + 1);
});
function updatenames($set, newIndex)
{
/*
updates input names in the form of
set-index.name
set-index
*/
var findnametype = function(inputname)
{
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') != -1)
{
var data1 = inputname.split('-');
var data2 = data1[1].split('.');
// [type, set, index]
return [1, data1[0], parseInt(data2[0])]
}
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') == -1)
{
var data = inputname.split('-');
return [2, data[0], data[1]];
}
return false;
};
var type = findnametype($set.find('input:eq(0)')[0].name);
$set.find('input, select').each(function()
{
var $input = $(this);
var oldname = $input[0].name;
var newname = false;
switch (type[0])
{
case 1: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
case 2: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
}
$input[0].name = newname;
});
return type;
}
That updatenames function is a variation of what I've been using lately. In this case, I check to find the format of the input name. I then increment the index.
The incrementing, as you've probably noticed, happens in the DOM. As a 'part 2' to my question, I'd like to learn how to have that object returned for me to then insert into the DOM.
Something like:
$newset = updatenames($newset, $('fieldset').length +1);
$newset.insertBefore($button);
Your help is appreciated. Cheers.
Have you considered using array-based field names? You wouldn't have to alter those at all:
<input type="text" name="users.firstname[]" />
<input type="text" name="users.lastname[]" />
whether this works for you will of course depend on what you're going to do with the fields.
<script type="text/javascript">
$(document).ready(function () {
$('.addmore').click(function () {
var fieldset = $(this).prev('fieldset');
var newFieldset = fieldset.clone();
incrementFieldset(newFieldset);
newFieldset.insertBefore($(this));
});
});
function incrementFieldset(set) {
$(set).find('input').each(function () {
var oldName = $(this).attr('name');
var regex = /^(.*)-([0-9]+)\.(.*)$/;
var match = regex.exec(oldName);
var newName = match[1] + '-' + (parseInt(match[2]) + 1) + '.' + match[3];
$(this).attr('name', newName);
});
}
</script>
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
<input type="button" class="addmore" value="Add" />
<fieldset>
<input index=1 var=user prop=firstname />
<input index=1 var=user prop=lastname />
</fieldset>
<fieldset>
<input index=2 var=user prop=firstname />
<input index=2 var=user prop=lastname />
</fieldset>
before you submit your form
get the custom attributes and construct your 'name' attribute
[update]
its jsp but shouldn't be hard for u to convert to php
<%
for (int i = 0; i < 1000; i++) {
%>
<fieldset>
<input index=<%=i%> var=user prop=firstname />
<input index=<%=i%> var=user prop=lastname />
</fieldset>
<%
}
%>
for the js code
$('button').click(function(){
$('input').each(function(i, node){
var $node = $(node);
$node.attr('name', $node.attr('var') + $node.attr('index') + "."+ $node.attr('prop'))
});
});