I want to add "i" to a input field when the red div is clicked, but the "i" that is added to the input field should not be viewable. If the green button is clicked the hidden "i" should be removed.
Here is my HTML live: http://jsfiddle.net/mtYtW/60/
My HTML:
<div class="input string optional">
<label for="company_navn" class="string optional">Name</label>
<input type="text" size="50" name="company[navn]" maxlength="255" id="webhost_navn" class="string optional">
</div>
<div style="width:30px;height:30px;margin-top:10px;display:block;background:green;">
</div>
<div style="width:30px;height:30px;margin-top:10px;display:block;background:red;">
</div>
How to create this functionality?
If you would like to associate data with a specific element, I suggest the .data() method of jQuery. Take a look at the jQuery docs. It's a much cleaner way of accomplishing your goal.
Here's a working Fiddle to get you started.
EDIT
Per the new requirement spelled out in the comments to your question, you can attach to the form submit event like this:
$('#yourForm').submit(function() {
if($('#webhost_navn').data('myData') == 'i')
{
var val = $('#webhost_navn').val();
$('#webhost_navn').val('i' + val);
}
});
NOTE: This code relys on the orginal code in my Fiddle.
It sounds like you want to associate some data with the input field, but not alter the input field's value. For that, you can use the data method:
$(document).ready(function() {
$('#redDiv').click(function() {
$('#webhost_navn').data('myData', 'i');
});
$('#greenDiv').click(function() {
$('#webhost_navn').data('myData', null);
});
});
You'll need to add id's to the red and green divs for the above example to work as is, respectively, redDiv and greenDiv. To retrieve the data you associate with the input, do this:
var myData = $('#webhost_navn').data('myData'); // Will equal 'i' or null
API Ref: http://api.jquery.com/data
EDIT: To append the "i" value to the input's value:
var myData = $('#webhost_navn').data('myData'),
val = $('#webhost_navn').val();
if (myData) {
$('#webhost_navn').val(myData + val);
}
Working example: http://jsfiddle.net/FishBasketGordo/e3yKu/
My update to your code here: http://jsfiddle.net/mtYtW/61/
Basically I gave your red/green button's id's and created a click event to add/remove the content. I also created a css definition for the color of the input box to be white so you don't see the text.
<div class="input string optional"><label for="company_navn" class="string optional"> Name</label><input type="text" size="50" name="company[navn]" maxlength="255" id="webhost_navn" class="string optional"></div>
<div id='green' style="width:30px;height:30px;margin-top:10px;display:block;background:green;"></div>
<div id='red' style="width:30px;height:30px;margin-top:10px;display:block;background:red;"></div>
css:
label {display:block;}
#webhost_navn{color:white};
js:
$("#red").live("click",function()
{
$("#webhost_navn").val("i");
});
$("#green").live("click",function()
{
$("#webhost_navn").val("");
});
Note if the goal is to post an "i" and have nothing else as a value (ie no user input) use <input type='hidden' id=webhost_navn > and use the same jquery code as above without the need for the css.
Related
I am having difficulty with a javascript that I need some help with. I have a form which sends to a php the exact amount of inputs to be filled, now I want to create a preview using jQuery/javascript but how can I catch all the fields dynamically.
Here is a portion of my form for reference:
<td>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-pencil"></i></span>
<input class="form-control" id="task" type="text" name="task" placeholder="Task Title">
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-pencil"></i>
</span>
<input class="form-control" id="description" type="text" name="description" placeholder="Task Description">
</div>
</td>
So, I added in PHP the name field + the number, this way I can get different names ie: task1, task2,...etc.
Now what I need to do is get the values using jQuery/javascript.
My thoughts so far is to declare the var (variable) inside a for() (loop)
var task = $('input[name=task]').val();
How can I get all values task1, task2. No one knows how many task fields the user will submit so I need to get the number of fields
Any help direction so I can figure this out
First of all, you don't need to give your input fields names like task1, task2, etc to distinguish among them on the server-side i.e on the PHP. You just need to give all of them a name attribute value like tasks[] And notice the brackets [] so you may have something like the following:
<input class="form-control" id="tasks[]" type="text" name="tasks[]" placeholder="Task Title">
...
<input class="form-control" id="tasks[]" type="text" name="tasks[]" placeholder="Task Title">
Like that automatically values in those fields will be posted as an array to the PHP and it is going to be received like the following in PHP script:
$tasks = $_POST['tasks'];
foreach ($tasks as $task){
echo $task;
}
Second By this way you will easily able to collect your inputs data using Javascript inorder to generate the preview by using getElementsByName method as follows:
function preview(){
output = "";
tasks = document.getElementsByName('tasks[]');
for (i=0; i < tasks.length; i++){
output += "<b>Title</b>: "+tasks[i].value+"<hr />";
}
panel = document.getElementById('panel');
panel.innerHTML = output;
}
Of course you can expand this solution to any number of fields in your form such as descriptions[].
A javascript DEMO: http://jsbin.com/kiyisi/1/
Using the Attribute Starts With Selector [name^="value"] and jQuery.each()
var tasks = $('input[name^=task]').val();
$.each(tasks,function(index, value){
//do something with the value
alert($(this).val());
});
edit
var tasks = $('input[name^=task]');
$.each(tasks,function(index, value){
//do something with the value
$('#Preview').append($(this).val());
});
Q: now I want to create a preview using jquery/javascript but how can I catch all the fields dinamically:
If you give them a class, you can get all fields with each:
$(".className").each(function() {
do something
Next, "catch" all fields... I'm assuming you may want the values of these fields too? Check this example for details, here is a snippet which loads the key:value pairs (form field name : value of field) into a map:
var map = {};
$(".activeInput").each(function() {
map[$(this).attr("name")] = $(this).val();
});
Print all values inside div (Here, I'm assuming you're talking about children values of div):
<div>
<span>Hi</span>
<span>Hello</span>
<span>Hi again</span>
</div>
$("div").children().each(function () {
console.log($(this).text());
});
OR
$("div span").each(function () {
console.log($(this).text());
});
I am trying to remove parent div if the input value is empty and show parent div if the input value is not empty?
the value of the input field is dynamic which means the value of it is the value of another input filed and I do this using javascript.
so far I haven't been able to show/hide the parent div for some reason. and I suspect the reason is because the value of the input field is dynamic which means the users are not typing anything in that input field. they are typing in another input filed and the value of the dynamic input field gets updated accordingly.
Here is what i have so far for show/hide the parent div:
HTML:
<div id="BOTTEXT2" class="secTxt">
<input type="text" class="sect2" id="sect2" style="border:none; background:none; " value="" size="12" readonly="readonly"/>
</div>
JAVASCRIPT:
<script type="text/javascript">
if(document.getElementById("sect2").value == ""){
document.getElementById("BOTTEXT2").style.display="block";
}
</script>
could someone please help me out with this?
Wrap your code in an event handler:
window.onload = function() {
var input = document.getElementById('sect2');
input.addEventListener('change', function() {
document.getElementById('BOTTEXT2').style.display = (input.value ? 'block' : 'none');
}, false);
};
This way, whenever you update the input, the div state changes accordingly.
I don't know if it will work for you, but follow the solution.
I created another input type out of main div to simulate the situation.
I used jQuery. After that, you can set your css of your way.
HTML
<div id="BOTTEXT2" class="secTxt">
<input type="text" class="sect2" id="sect2" style="border:none; background:none; " value="BSAU145D" size="12" readonly="readonly"/>
</div>
<input type="text" id="sect1">
Javascript (jQuery)
$(document).ready(function(){
$('#sect1').keyup(function(){
if($('#sect1').val() == 'test') {
$('#BOTTEXT2').css({'display':'none'});
} else {
$('#BOTTEXT2').css({'display':'block'});
}
});
});
Here is the fiddle
Given the following html:
<div class="product">
<span class="name">Product name</span>
<span class="price">Product price</span>
</div>
<input type="button" class="button" value="Purchase" onclick="myfunction()" />
<input type="hidden" name="p-name" value="">
<input type="hidden" name="p-price" value="">
I am trying to build a function in javascript that takes the value from span.name (span.price) and adds it to input p-name (input p-price).
How can you do that?
Apperantly http://api.jquery.com/val/ is not working as expected.
EDIT
Thanks all for answering!
I've corrected the html error you guys pointed out in the comments.
Try this:
$('.product span').each(function () {
var selector = 'input[name=p-' + this.className + ']';
$(selector).val(this.innerHTML);
});
Fiddle
You will need a button or something to fire the copying:
<input type="button" id="copy_values" value="Copy the values" />
and your javascript
$(document).ready(function(){
$("#copy_values").click(function(){
//Change the value of the input with name "p-name" to the text of the span with class .name
$('input[name="p-name"]').val($('.name').text());
$('input[name="p-price"]').val($('.price').text());
});
});
For span we use text() function instead of val()
.val() is used when we use input and .text() is used when we use span in HTML.
Reference link : http://api.jquery.com/text/
That's going to be hard to click to a HIDDEN field.
If you change input type to text, then in onclick you can write: this.value=document.getElementById('name').innerHTML; (to use this, you have to add ID with name to your )
OR, you can create a seperate button, and onclick method can be fired.
So every 'special-input' div contains an input field. I am trying regulate when each information can be entered into each input field.
Initially, I would like the first input field from the top to be enabled, while the rest of the input fields below it be disabled.
OnChange of input field 1, I would like for the next input field below it to be enabled, while the rest disabled. OnChange of input field 2, I would like for input field 3 to become enabled, while the rest remain disabled, etc...
I know I can use JQuery's attr() to enable input fields when needed, but I am unsure how to apply the logic to accomplish this as JQuery is quite new to me.
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
<div class="special-input"><input type="text" /></div>
......
......
......
<div class="special-input"><input type="text" /></div>
// Cache the inputs, this is a good way to improve performance of your
// jQuery code when re-using selectors.
var $inputs = $('.special-input :input');
// Disable all except the first input
$inputs.not(':first').attr('disabled', 'disabled');
$inputs.each(function(i) {
// For each input, bind a change event to enable the next input,
// if the user presses enter, the next textbox will receive focus. if the user
// presses tab, the following input won't receive focus, so you'll have to add
// code if you want this to work.
$(this).on('change', function() {
// Get the index of the current input element we're looking at,
// We need to re-wrap the $input[i] element as it is now a normal
// DOM element.
var $nextInput = $($inputs[i + 1]);
$nextInput.removeAttr('disabled').focus();
});
});
Edit: You can see a working example at http://jsfiddle.net/dFZEq/11/
Edit 2:
To enable the next line's set of elements after a certain condition is met, use this:
var $specialInputs = $('.special-input');
// don't disable the first line's input elements.
$specialInputs.not(':first').find(':input').attr('disabled', 'disabled');
$specialInputs.on('change', function() {
var $this = $(this);
if ($this.find(':input').filter(function() {
// you can change this filter to match any condition you
// like, for now we'll just make sure all inputs have a non-empty value
return $(this).val() == '';
}).length == 0) {
var $nextInputSet = $($specialInputs[$this.index() + 1]).find(':input');
// enable the next set of elements
$nextInputSet.removeAttr('disabled');
// focus your element here, requires more work
$nextInputSet.first().focus();
}
});
Example at http://jsfiddle.net/tFG5W/
I've not tested the following code, but should look something like this :
$(".special-input").bind("change",function(event){
$(this).attr("disabled","disabled");
$(this).next().removeAttr("disabled").focus();
});
My html form has optional items to display as follows:
<span class="Optional Command1 Command2">
<label for="elem1">Elem 1:</label><input type="text" id="elem1" /><br />
</span>
<span class="Optional Command1 Command3">
<label for="elem2">Elem 2:</label><input type="text" id="elem2" /><br />
</span>
An html select element is used to select Command1, Command2 or Command3 which corresponds to the class for the above html elements.
When the select change event happens, it calls the following function:
function showOptional(commandName) {
$('.Optional').hide(); // clear out optional inputs
$('.Optional').filter('.' + commandName).show(); // show relvant inputs
}
However for Command1, which is included in the class for both elem1 and elem2 above, only the first input element will be displayed, but I thought the jQuery selector would apply both.
In other words, for the above html the showOptional('Command1') Javascript function only displays the first span with Command1, but not the second span with Command1. Why not both?
This works for me:
function showOptional(commandName) {
$('.Optional').hide(); // clear out optional inputsinputs
$('.Optional.' + commandName).show(); // show relvant
}
showOptional('Command1');
Fiddle: http://jsfiddle.net/sYXuM/1/
However, your original approach works for me as well: http://jsfiddle.net/sYXuM/2/
I just ran a performance test and the following code is faster than your original approach and my suggestion above:
function showOptional(commandName) {
$('.Optional').hide().filter('.' + commandName).show();
}