Update placeholder by id using jQuery - javascript

I have an input field in html which is created 'dynamically' in a function say :
'<input id="id1'+var1+'" name="id1" type="text" placeholder="Provide IP"/>'
In the same function in javascript, I'm trying to change the placeholder text by :
$("#id1"+var1).attr("placeholder",arr[i]);
It doesn't work!!The array arr also gets updated in the function
Also further options like :
$("#id1"+var1).attr("placeholder",arr[i]).blur();
$("#id1"+var1).attr("placeholder",arr[i]).placeholder();
$("#id1"+var1).attr("placeholder",arr[i]).val("").focus().blur();
doesn't work. It is retaining previous placeholder text only!! How to resolve this? I'm using Google Chrome

Your are missing to do the change after the dom is loaded. Try this:
$(document).ready(function(){
$("#id1").attr("placeholder","IP changed");
})
$(document).ready(function() {
var i = 0;
var j = i - 1
var myArray = ["firts text", "second text", "and so on"]
$("#button").click(function() {
if (i > 2) {
i = 0;
}
$('input').each(function() {
if ($(this).attr('placeholder') == "Provide IP" || $(this).attr('placeholder') == myArray[j]) {
$(this).attr("placeholder", myArray[i]);
return false;
}
})
i++;
j++;
if (j > 2) {
j = i - 1;
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="id1" name="id1" type="text" placeholder="Provide IP" />
<input type="button" id="button" value="Click me" />

<input id="id1"+var1 name="id1" type="text" placeholder="Provide IP"/>
you have the " in the wrong place on id.

Related

Specify first character of input

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...

Hiding multiple form fields using checkboxes

I have this code that I need to edit so I can use it on multiple chkBox's and txtBox's.
Currently I can only hide one input field with one check box.
I know HTML and CSS but I am not familiar with JS.
I would like to be able to add a number at the end of each ID.
chkBox1, chkBox2, chkBox3... txtBox1, txtBox2, txtBox3...
Do I need to change getElementById to getElementsByTagName()?
JSFIDDLE for some reason it does not work here...?
This is my current code which hide the text field unless the checkbox is checked:
function showHide(){
var chkBox = document.getElementById("chkBox");
var txtBox = document.getElementById("txtBox");
if (chkBox.checked){
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}
The reason your code wasn't working is because it was running onLoad. Your DOM and the onclick were created before the load was complete. You could just move your code into your <head></head> tags and it will work as is. See here, all I did was select the "No wrap - in head", no code changes.
You could also continue to have your javascript run onLoad and remove your onclick and add an eventlistener in the javascript like this:
JSFiddle
var txtBox = document.getElementById("txtBox");
document.getElementById("chkBox").addEventListener("click", function() {
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
});
If you have multiple instances of this, I would change your DOM a bit sort of like this:
<form>
<div class="option">
<input type="text" name="txtBox1" class="hiddenInput" />
<br/>
<input type="checkbox" name="chkBox1" id="chkBox1" class="showHideCheck" />
<label for="chkBox1">Click me to show the text box</label>
</div>
<div class="option">
<input type="text" name="txtBox2" class="hiddenInput" />
<br/>
<input type="checkbox" id="chkBox2" name="chkBox2" class="showHideCheck" />
<label for="chkBox2">Click me to show the text box</label>
</div>
</form>
and do your JQuery like this (since you previously tagged jquery):
$(".hiddenInput").hide();
$(".showHideCheck").on("change", function() {
$this = $(this);
$input = $this.parent().find(".hiddenInput");
if($this.is(":checked")) {
$input.show();
} else {
$input.hide();
}
});
JSFiddle
Or with pure javascript and the similar DOM as above:
var checkBoxes = document.getElementsByClassName("showHideCheck");
for (var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('click', function () {
var txtBox = getAssociatedTextBox(this);
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}, false);
}
function getAssociatedTextBox(ele) {
var childNodes = ele.parentNode.childNodes;
for (i = 0, j = childNodes.length; i < j; i++) {
if (childNodes[i].className == "hiddenInput") {
return childNodes[i];
}
}
}
JSFiddle
Try this,
Javascript
$(document).ready(function(){
$("input[type=checkbox]").change(function(){
var oTxt = $("#txtBox" + $(this).attr("id").replace("chkBox", ""));
if($(this).is("checked"))
oTxt.show()
else
oTxt.hide();
});
});
HTML
<input type="checkbox" id="chkBox1"/>
<input type="textbox" id="txtBox1"/>
<input type="checkbox" id="chkBox2"/>
<input type="textbox" id="txtBox2"/>

Get array text filed value via javascript

in my process text filed in array i need to get the value via javascript but my code is not working my code following
<input type="text" id="itemid[]" name="itemid[]" class="span12"/>
and javascript code is
function getstock()
{
var itemidarr=document.getElementById('itemid[]');
if(itemidarr!= null)
{
alert(itemidarr.length);
}
}
any other solution for this
The IDs can't contain brackets, these: [], so:
<input type="text" id="itemid1" name="itemname1" class="span12"/>
<input type="text" id="itemid2" name="itemname1" class="span12"/>
<input type="text" id="itemid3" name="itemname1" class="span12"/>
Then you have to loop through the IDs:
function getstock()
{
for(var i=1; i<=3; i++){
var itemidarr=document.getElementById("itemid"+i);
if(itemidarr!= null) alert(itemidarr.length);
}
}
The id attribute here cannot contain [ ].
Put your textboxex in "fieldset tag"
Like:
<fieldset id="field">
//Put you text boxes here<input type='text'>
</fieldset>
Access these by:
document.getElementById("list....").getElementsByTagName("input")[indexoftext];
indexoftext is the text box you wan to choose.
Hope it helps!
you can try something like this below
<input type="text" id="itemid" name="itemid" class="span12"/>
function getstock()
{
var itemidarr = document.getElementsByName('itemid');
for(var i = 0; i < itemidarr.length; i++){
var item=document.getElementsByName('itemid')[i].value;
if(item!= null)
{
alert(item);
}
}
}
You can't make an array to fill in an input text, only for input like radio or checkbox.
Text input only accept a single string.
function getstock() {
var a = [];
jQuery.each(this, function(i, field){
a.push($.trim(field.value));
});
return a;
}
can u use this code
i got the result
function getstock1()
{
alert("test");
var itemidarr = document.getElementsByName('itemid[]');
for (var i = 0; i < itemidarr.length; i++)
{
alert(itemidarr[i].value);
}

Delete form fields using Javascript

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);
}

What's the best way to update the input names when dynamically adding them to a form?

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'))
});
});

Categories

Resources