(1) I've a scenario where there are some checkbox with a "Other" (user typed option) checkbox
(2) When clicking on the checkbox of "Other", a input field will come and cover the "Other" text.
(3) User can type at there and there is an "ok" button beside the checkbox.
(4) When user click the "Ok" button, input field will be gone and user typed text will come at the place of previous "Other" text. At the same time new "Other" fields should come after previous. Also previous "Other" shouldn't expand any more as it's not "Other" anymore(for example, it's now Black).
To make this, I've written jQuery like this:
$('.otherOption input[type="checkbox"]').click(function() {
$(this).closest('.otherOption').find('.box').toggle();
});
$('.ok').click(function() {
var value = $('.optionInput').val();
$('.box').hide();
$('.otherOption p').text(value);
$('.otherOption').removeClass('otherOption');
$(this).closest('.otherOption').append('<div class="block otherOption"><input type="checkbox" /> <p>Other</p><div class="box"><input type="text" value="" placeholder="Provide your option" class="optionInput" /><button class="ok">Ok</button></div></div>');
});
I think, I can write some script correctly. But, as I ain't good at jQuery, I can't write the jquery selector(.closest(),.parents(),.next() etc) that's why, my script is not working. So, please help me to make my script correct. Thanks in advance
My fiddle
Good start. A couple things to make this work the way you want.
You code $('.otherOption').removeClass('otherOption'); removes all instances of the otherOption class which is why your append isn't working.
If you removed the line mentioned above, you're appending the new checkbox inside the wrapper of the other checkbox which I can imagine isn't the desired result. I would imagine you want the new checkbox to come .after() the old otherOption box.
These being said remove this line:
$('.otherOption').removeClass('otherOption');
and change your $(this).closest('.otherOption')... to
$(this)
.closest('.otherOption')
.removeClass('otherOption')
.after('<div class="block otherOption"><input type="checkbox" /> <p>Other</p><div class="box"><input type="text" value="" placeholder="Provide your option" class="optionInput" /><button class="ok">Ok</button></div></div>');
A side note - cause you'll wonder later - your .click() function's won't work more than once. .click() binds to all matching objects on the page load. So any items added dynamically after page load will not work. Look into using jQuery's .on() method. This will ensure you're code works on all matching items no matter when they're added to the DOM.
Edit: One other thing, I noticed that when you repetitively added items, it always added the text from the first box b/c you are not removing the used text boxes. I've added $(this).closest('.box').remove(); to the end of the JS code to fix this issue.
Here's a working fiddle with jQuery's .on() implemented http://jsfiddle.net/a695jk2d/4/
Don't just copy and paste it, understand it.
It might make more sense to simply insert a new structure above your already existing "Other" option. Why replace it's text, and add a whole new 'other' option block? This version will insert a new option above the "Other" option. This way you also only need to bind to the element once as well.
$( '.ok' ).click(function () {
var value = $( '.optionInput' ).val();
$( '.optionInput' ).val('');
$( this ).parent().parent().find( '.box, p' ).toggle();
$( '.otherOption input[type="checkbox"]' ).attr( 'checked', false );
$( '#optionContainer' ).append(
'<div class="block"><input type="checkbox" /> <p>' + value + '</p></div>'
);
});
jsFiddle
Related
I want to allow users to dynamically create as many input fields as they want within the format that I supply to them.
I need the features below:
There should be a button to add more fields
There should be a button next to each field to delete the field
Is there any method which satisfies my needs?
I've already used the append() method in JavaScript but I was not able to delete the fields using a button next to it.
onclick on a button:
$( '#some_div' ).append( '<input type="text" name="tel[]" class="form-control">' );
I've heard something about grids but could not find anything relevant.
append() will work for adding fields. To subtract fields you could use remove().
One possible method of performing this action is done by wrapping the field and the delete button in a div, making it easy to target the entire group for deletion. jQuery's closest() finds the closest element up the DOM that matches your search, relative to the location you're searching from.
$("#add-field").click(function() {
$("#some_div").append('<div class="input-block"><input type="text" name="tel[]" class="form-control"><input type="button" class="remove-field" value="-"></div>');
});
$(document).on("click", ".remove-field", function() {
$(this).closest(".input-block").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" id="add-field" value="+ Add Field">
<div id="some_div"></div>
I have a textbox which is hidden using display = none. I am trying to change it to visible on some condition, however it does not seem to work. I have checked that the control is going to the change event. I have tried various ways to get it to work, the 3 ways that I have tried are within the $('body')
colValue = "<input id ='val' class='value' value ='" + field.Value + "'style = 'display: none'/>";
I have tried these different things to get it to show the control. None of these work.
$('#val').css("display", "block");
$('#val').css('display', 'inline');
$('#val').css({ "display": "inline" });
Am I missing something?
Edit
So your issue appears to be that the box isn't appearing after a change event. Ensure that your HTML IDs are unique, and that your change handler is getting wired up after the DOM is ready. If those are all true the issue likely exists outside of the code fragment you've shown, since the code you've provided should work. One thing to note is that the change event doesn't get fired until the control being changed loses focus. If it's another textbox, you have to click out of the box before the event gets fired. See the example below (note: I'm using show to update the element's visibility since that's more idiomatic, but it should be functionally equivalent to what you attempted.)
$(function() {
$('body').on('change', '.condition', function () {
$('#val').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Text Box 1 <input id ='val' class='value' value='test' style='display: none' type='text'/> <br />
Text Box 2 <input class='condition' type='text'/>
There's no variable named inline in your application. Wrap it in quotes and make it a string. Additionally, you're trying to change the style, so you have to call the appropriate method (See docs for css method):
$("#val").css("display", "inline");
I'm using Dojo 1.6 and want to select all the text of a textbox only at the first click. I know I can use dojo.byId("id").select(); to select the whole text, but the problem is that you can't make a subselection of text anymore. I've provided a small code example to show the problem.
require(["dojo/parser", "dijit/form/TextBox"]);
require(["dojo/query", "dojo/on", "dojo/domReady!"], function(query, on) {
query("#firstname").on("click", function(evt) {
// this will not work because I want to select 1 or more characters
if (!dojo.byId("firstname").select())
dojo.byId("firstname").select();
});
});
And the fiddle: http://jsfiddle.net/3CLz9/
So the main problem is that I can't determine if one or more characters are selected.
You could use the dojo/on module's once() function. But I don't think that this is what you want. I suppose you want to select the text each time the input field gains focus. If you want this, you should be using the onFocus event, (so replace the "click" by "focus").
The only problem now is that after you select the text, the default event will move your cursor to the selected position and unselect your text (you will see it blink). To solve that you should also bind an mouseup event handler that cancels when you just gained focus. For example:
query("#firstname").on("focus", function(evt) {
this.select();
on.once(this, "mouseup", function(evt) {
evt.preventDefault();
});
});
I also updated your fiddle.
I just noticed that you're actually using a dijit/form/TextBox widget (didn't work on your JSFiddle so that's why I didn't notice it), but you can easily do this with the selectOnClick property. Add it to your data-dojo-props and it will work.
For example:
<input type="text" name="firstname" value="testing testing"
data-dojo-type="dijit/form/TextBox"
data-dojo-props="trim:true, propercase:true, selectOnClick: true" id="firstname" />
Here is your fiddle (with a working textbox widget). If you want to do the same thing for Dojo versions below 1.7, you can do that like described in this fiddle.
I have a form setup with dojo 1.5. I am using a dijit.form.ComboBox and a dijit.form.TextBox
The Combobox has values like "car","bike","motorcycle" and the textbox is meant to be an adjective to the Combobox.
So it doesn't matter what is in the Combobox but if the ComboBox does have a value then something MUST be filled in the TextBox. Optionally, if nothing is in the ComboBox, then nothing can be in the TextBox and that is just fine. In fact if something isn't in the Combobox then nothing MUST be in the text box.
In regular coding I would just use an onBlur event on the text box to go to a function that checks to see if the ComboBox has a value. I see in dojo that this doesn't work... Code example is below...
Vehicle:
<input dojoType="dijit.form.ComboBox"
store="xvarStore"
value=""
searchAttr="name"
name="vehicle_1"
id="vehicle_1"
/>
Descriptor:
<input type="text"
dojoType="dijit.form.TextBox"
value=""
class=lighttext
style="width:350px;height:19px"
id="filter_value_1"
name="filter_value_1"
/>
My initial attempt was to add an onBlur within the Descriptor's <input> tag but discovered that that doesn't work.
How does Dojo handle this? Is it via a dojo.connect parameter? Even though in the example above the combobox has an id of "vehicle_1" and the text box has an id of "filter_value_1", there can be numerous comboboxes and textboxes numbering sequentially upward. (vehicle_2, vehicle_3, etc)
Any advice or links to resources would be greatly appreciated.
To add the onBlur event you should use dojo.connect():
dojo.connect(dojo.byId("vehicle_1"), "onBlur", function() { /* do something */ });
If you have multiple inputs that you need to connect this to, consider adding a custom class for those that need to blur and using dojo.query to connect to all of them:
Vehicle:
<input dojoType="dijit.form.ComboBox"
store="xvarStore"
class="blurEvent"
value=""
searchAttr="name"
name="vehicle_1"
id="vehicle_1"
/>
dojo.query(".blurEvent").forEach(function(node, index, arr) {
dojo.connect(node, "onBlur", function() { /* do something */ });
});
In the function that is passed to dojo.connect you could add in some code to strip out the number on the end and use it to reference each filter_value_* input for validation.
dojo.connect()
Combobox documention
onBlur seems to work just fine for me, even in the HTML-declared widgets. Here's a very rudimentary example:
http://jsfiddle.net/kfranqueiro/BWT4U/
(Have firebug/webkit inspector/IE8 dev tools open to see console.log messages.)
However, for a more ideal solution to this, you might also be interested in some other widgets...
http://dojotoolkit.org/reference-guide/dijit/form/ValidationTextbox.html
http://dojotoolkit.org/reference-guide/dijit/form/Form.html
Hopefully this can get you started.
this is a small, but very annoying, glitch in my form.
I have a checkbox, that if clicked displays others checkboxes and input fields for the user to add more information. If this trigger checkbox is unclicked, the extra options dissapear.
However (the plot thickens), if another checkbox is checked in the form, the trigger checkbox can be checked and the extra options appear, but if unchecked the extra option won't dissapear!
(Sorry that was long winded, but i wanted to be clear!)
Here is my simple Jquery code:
$(function() {
var boxes = $('.obstruct-opt');
boxes.hide();
var ob = $('li.obstructionOptions').children().eq(0);
ob.change(function() {
if ($('$(this):checked').val()) {
boxes.show();
}
else {
boxes.hide();
}
});
});
I have tried different ways of checking if the trigger is checked or not, but any suggestions are welcome.
Edit
HTML as requested: (although simplified as my ASP.Net repeater control generated it)
<ul>
<li class="obstructionOptions">
<span>
<input id="Obstruction" type="checkbox" name="Obstruction" />
<label for="Obstruction">Obstruction</label>
</span>
<span class="obstruct-opt">
<input id="WeatherProof" type="checkbox" name="WeatherProof"/>
<label for="WeatherProof">WeatherProof</label>
</span>
<span class="obstruct-opt">
<input id="WeatherProofFlap" type="checkbox" name="WeatherProofFlap"/>
</span>
</li>
<li class="obstruct-opt">
<span>Obstruction Notes</span>
<textarea name="ObstructionNotes" rows="7" cols="50" id="ObstructionNotes"/>
</li>
</ul>
Hope it helps!
Update:
substituting the if condition to
if ($(this).is(":checked")) {
doesn't trigger anything, no appearing or disappearing acts in sight.
Thanks for the suggestion tho, maybe with my html you can discern why?
Update
Ok after posting my HTML i realised ASP.Net has been stitching me up!
As you can see i select the 'ob' object as the first child, but the first child is a generated span! ASP has been wrapping my checkboxes in spans all this time and i never suspected! shrewd!
I have used this code in the end:
$('ul li.obstructionOptions span').children().eq(0).click(function() {
if ($(this).is(":checked")) {
boxes.show();
}
else {
boxes.hide();
}
});
Thank you to adamantium as this solved the prod perfectly!
Problem Solved!
Do not to trust ASP.Net with my markup!!!
What about replacing
if ($('$(this):checked').val())
with
if ($(this).is(':checked'))
is
Checks the current selection against
an expression and returns true, if at
least one element of the selection
fits the given expression.
Edit:
Replace
var ob = $('li.obstructionOptions').children().eq(0);
with
var ob = $('ul li.obstructionOptions span').children().eq(0);
and
<textarea name="ObstructionNotes" rows="7" cols="50" id="ObstructionNotes"/>
with
<textarea name="ObstructionNotes" rows="7" cols="50" id="ObstructionNotes"></textarea>
and your code works fine.
Working Demo
It might have something to do with this line:
if ($('$(this):checked').val()) {
AFAIK, that won't do anything useful. You probably want this:
if ($(this).is(":checked")) {
ob.change(
A checkbox's onchange doesn't fire in IE until it's unfocused. For this reason it's usual to use onclick instead.
$('$(this):checked').val()
Doesn't work for two reasons. Firstly, you've included $(this) as part of the string. A dollar and brackets don't mean anything to selectors so jQuery won't match anything. You've already got the this object you want; you don't need to select anything more. Secondly, val() on a checkbox gets the value of that checkbox, not whether it is checked or not. This is the value attribute, or on if you haven't specified one.
Whilst you could test for checkedness using if ($(this).is(':checked')), it's more readable and much quicker to just use the standard DOM checked property. You don't have to shoehorn everything you do into jQuery.
ob.click(function() {
if (this.checked)
boxes.show();
else
boxes.hide();
});