How can I create this switch behaviour via Javascript? - javascript

First of all, I am really sorry that I could not give specific title about the issue. I have a .net 4.6.1 view page.
I want to create this feature.
Depending on the DepositType, the DefaultDeposit should display either a £ sign or %.
One of the logic, I already tried was to create another property called DefaultDepositPercent. Create a Input Box which is hidden underneath and use Jquery to display or hide this Input Box. Then in my service layer, pass the value inputted in the DefaultDepositPercent to DefaultDeposit.
However, there was an inconvenience that the mvc form also passes the DefaultDeposit value as 0. And there is also an issue of someone fiddling with the Javascript.
I have googled but could not find any answers. It is likely because I could describe the issue in few words.
Any direction would be helpful. Thanks

In bootstrap we just have to place the span tag above or below the input element to get the Prefix or Postfix effect. More Details Here
So the idea is first not to have this post / prefix span tag initially but add it either on DOM ready event or when the drop down selection changes using Jquery insertBefore and insertAfter. Here is a working sample. Hope this is helpful.
$(function() {
SetUpDepositTextBox(); // set up the input box once when DOM is ready
$('.DepositType').on('change', function() {
SetUpDepositTextBox(); // set up the text box when ever the dropdown changes
});
});
function SetUpDepositTextBox() {
$('#depositDefaultWrapper span').remove();
var $this = $('.DepositType');
if ($this.val() == "Amount") {
$('<span class="input-group-addon">£</span>').insertBefore('#depositDefaultWrapper input');
} else {
$('<span class="input-group-addon">%</span>').insertAfter('#depositDefaultWrapper input');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
Deposit Type
<select class="DepositType form-control">
<option value="Amount">Amount</option>
<option value="Percentage">Percentage</option>
</select>
Default Deposit
<div id="depositDefaultWrapper" class="input-group">
<input type="text" class="form-control" value="10">
</div>

Related

JQuery Masked Input plugin not working for an area code

I'm working with JQuery Masked Input plugin. I have a mask for an area code which simply inserts parenthesis at the beginning and at the end of 3 digits like: (123). When my area code input field has a 3 digit value, the plugin inserts the left parenthesis but not the right one. I would expect it to insert both parenthesis or none of them. If you type anything in the textbox, it automatically fills the right parenthesis. Here is an example:
$(function(){
$('#areacode').mask('(000)', { placeholder: '(___)'});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.13.4/jquery.mask.min.js"></script>
<input type="text" id="areacode" value = "123"/>
Could anybody let me know the source of this behavior?
Thanks!
Alright, so I've sort of found a solution. It's not pretty, but triggering the keyup event seems to fix it.
$(function(){
$('#areacode').mask('(000)', { placeholder: '(___)'}).trigger('keyup');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.13.4/jquery.mask.min.js"></script>
<input type="text" id="areacode" value = "123"/>

Materalize CSS error labels

Materalize already supports validation for input fields such as email, but I would like to validate input fields such as passwords on the fly. Basically this means adding the error or success label through javacript.
My success so far has been poor. When I call the change() JS function and try to addClass('valid') for example, nothing happens and from what I can see, the class doesn't even appear in the HTML. I know the function is working because if I add a nonsense class like 'test', it does display in the HTML.
Is it not as simple as adding 'valid' or 'invalid' - do I need to meet other criteria before the label will appear?
Any help will be much appreciated.
My solution was to include the error labels as below:
<div class="input-field col s9 offset-s1">
<i class="material-icons prefix">perm_identity</i>
<input id="register_user" name ="register_user" type="text">
<label id="reg-user-error" style="display:none" for="register_user" data-error="short" data-success="good">Username</label>
<label for="register_user">Username</label>
</div>
But making sure to hide the label by default. Then I only had to modify the classes with javascript and show the label. If you don't hide by default, any input automatically validates the label. My JS is:
$('#register_user').on('change',function()
{
if($('#register_user').val().length > 7)
{
if($('#register_user').hasClass('invalid'))
{
$('#register_user').removeClass('invalid');
}
$('#register_user').addClass('valid');
$('#reg-user-error').addClass('active');
$('#reg-user-error').show();
}
else if($('#register_user').val().length < 8)
{
if($('#register_user').hasClass('valid'))
{
$('#register_user').removeClass('valid');
}
$('#register_user').addClass('invalid');
$('#reg-user-error').addClass('active');
$('#reg-user-error').show();
}
});

Populate a hidden form field using the div of a drop menu (drop down menu is created using divs not select, option etc)

I have a form.
Please note I must use divs for creating the form drop down and not the select option method etc. It just has to be done that way. The code is below.
<form action="url.asp" method="get">
<div class="search-button"><i class="fa fa-search"></i><input type="submit" /></div>
<div class="search-drop-down">
<div class="title"><span>Choose Category</span><i class="fa fa-angle-down"></i></div>
<div class="list">
<div class="overflow">
<div class="category-entry" id="Category1">Category One</div>
<div class="category-entry" id="Category2">Category Two</div>
</div>
</div>
</div>
<div class="search-field"><input type="text" name="search-for" id="search-for" value="" placeholder="Search for a product" /></div>
<input type="hidden" id="ChosenCategory" name="ChosenCategory" value="CATEGORY1 OR CATEGORY2 (WHICHEVER SELECTED)" />
</form>
As shown in the code above I need to populate the hidden field value as per the chosen option which the user selects in the drop down.
I have used about 20 different variations of getElementById or onFocus functions but cannot get it to work.
The only thing I can get to work is the following JavaScript and it just populates the hidden field value with the first id ignoring completely which one has actually been selected(clicked) by the user;
var div = document.getElementById('DivID');
var hidden = document.getElementById('ChosenCategory');
hidden.value = div.innerHTML;
I'm running classic asp so if there is a vbscript way then great, otherwise if I have to use JavaScript to do it then as long as it does the job I'll be happy still.
A click handler on the options could be used to update the value.
No jQuery or any other external library is needed. Below is a working example. Of course, in your case the input element could be of type hidden, but I made it text here for the sake of demonstration.
//Add the click handlers
var options = document.getElementsByClassName('option');
var i = 0;
for (i = 0; i < options.length; i++) {
options[i].addEventListener('click', selectOption);
}
function selectOption(e) {
console.log(e.target);
document.getElementById('output').value = e.target.id;
}
div {
padding: 10px;
}
div.option {
background-color: #CCC;
margin: 5px;
cursor: pointer;
}
<div>
<div class="option" id="Category1">Category One</div>
<div class="option" id="Category2">Category Two</div>
</div>
<input type="text" id="output" />
You should be able to achieve what you're after with a fairly simple setup involving listening for clicks on two separate <div> elements, and then updating an <input> based on those clicks.
TL;DR:
I've put together a jsfiddle here of what it sounds like you're trying to make work: https://jsfiddle.net/e479pcew/5/
Long version:
Imagine we have 2 basic elements:
A dropdown, containing two options
An input
Here's what it might look like in HTML:
<div class="dropdown">
<div id="option-one">Option 1</div>
<div id="option-two">Option 2</div>
</div>
<input type="text" id="hidden-input">
The JavaScript needed to wire these elements up should be fairly easy, but let me know if it doesn't make sense! I've renamed things throughout to make things as explicit as possible, but hopefully that doesn't throw you off.
One quick thing - this is an incredibly 'naive' implementation of this idea which has a lot of potential for refactoring! However I just wanted to show in the most basic terms how to use JavaScript to make this stuff happen.
So here we go - first things first, let's find all those elements we need. We need to assign variables for the two different dropdown options, and the hidden input:
var optionOne = document.getElementById("option-one");
var optionTwo = document.getElementById("option-two");
var hiddenInput = document.getElementById("hidden-input");
Cool. Next we need to make a function that will come in handy later. This function expects a click event as an argument. From that click event, it looks at the id of the element that was clicked, and assigns that id as a value to our hiddenInput:
function valueToInput(event) {
hiddenInput.value = event.target.id;
}
Great - last thing, let's start listening for the clicks on specific elements, and if we hear any, we'll fire the above valueToInput function:
optionOne.addEventListener("click", valueToInput, false);
optionTwo.addEventListener("click", valueToInput, false);
That should get you going! Have a look at the jsfiddle I already linked to and see if it makes sense - get in touch if not.
Are you allowed to use JQuery in this project? It would make your life a lot easier. You can detect when a div is clicked and populate the hidden field.
This could do it:
$(document).ready(function() {
$('.category-entry').click(function() {
$('#ChosenCategory').val($(this).text()); }); });

ColdFusion: Modify combobox options in cfgrid

I have a <cfgrid> with one <cfgridcolumn>. I'm using the values attribute for that column:
<cfform>
<cfgrid name="grdBrokers"
format="html"
bind ="cfc:CFC.Brokers.getGridData ( {cfgridpage},{cfgridpagesize},{cfgridsortcolumn},{cfgridsortdirection})"
onChange="cfc:CFC.Brokers.editGridData( {cfgridaction},{cfgridrow},{cfgridchanged})"
selectMode = "edit">
<cfgridcolumn name="name" header="Name" values="Item1,Item2" >
</cfgrid>
</cfform>
The values attribute causes a combobox to appear when the user edits a cell in the Name column:
I need to dynamically (without reloading the page) change the options list of that combobox. After much research (stackoverflow.com, raymondcamden.com, etc.) I concluded there are no ColdFusion methods for doing this, so I figured I'd use JavaScript. To locate the id for the combobox I viewed the HTML source for my page and found the following:
<form name="CFForm_1" id="CFForm_1" action="/index2.cfm" method="post" onsubmit="return _CF_checkCFForm_1(this)">
<div id="cfgrid1344103796431" style="border: 1px solid #cccccc; overflow: hidden;"></div>
<select id='cf_grid_select0' class='ygrid-editor'>
<option value='Item1'>Item1</option>
<option value='Item2'>Item2</option>
</select>
<div>
<input type="hidden" name="__CFGRID__CFForm_1__grdBrokers" value="" /></div>
</form>
So, the id I want is cf_grid_select0. However, this element isn't found by document.getElementById(). I have also inspected the page using FireBug and can't find the cf_grid_select0 element on the DOM tab. It's contained in document.body.innerHTML as raw HTML text, but not as its own element in the DOM.
Here is my code that attempts to find cf_grid_select0:
<script type="text/javascript">
function find( ) {
var cbxFind = document.getElementById( 'cf_grid_select0' );
if ( cbxFind ) alert( "Found!" );
else alert( "Not found!" );
}
</script>
<form>
<input id="btnFind" type="button" onclick="find();" value="Find">
</form>
When I click the Find button, I get a popup saying "Not found!".
My question is: using JavaScript or jQuery, how can I locate a <select> that my browser obviously knows about, but doesn't seem to be in the DOM? I suspect ColdFusion.getGridObject() might be what I'm looking for, but I can't find a way to select the combobox using that method, either.
Thank you!
UPDATE:
It appears that ColdFusion is using ExtJS to transform the <select> into a ComboBox after the page loads, apparently removing the <select> from the DOM. I am now researching how to locate a ExtJS ComboBox.
I would almost certainly use jQuery! Try this:
<script>
$(document).ready(function() {
var $mySelect = $("#cf_grid_select0");
alert("I found it..." + $mySelect.attr("id"))
});
</script>
Good luck.
NINJA EDIT
If you're viewing the real source then it IS in the DOM. If you're viewing a "generated" JS kind of source, then it is tricky, but I think jQuery can detect new elements added to the DOM anyway.

How to focus on a form input text field on page load using jQuery?

This is probably very simple, but could somebody tell me how to get the cursor blinking on a text box on page load?
Set focus on the first text field:
$("input:text:visible:first").focus();
This also does the first text field, but you can change the [0] to another index:
$('input[#type="text"]')[0].focus();
Or, you can use the ID:
$("#someTextBox").focus();
You can use HTML5 autofocus for this. You don't need jQuery or other JavaScript.
<input type="text" name="some_field" autofocus>
Note this will not work on IE9 and lower.
Sure:
<head>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#myTextBox").focus();
});
</script>
</head>
<body>
<input type="text" id="myTextBox">
</body>
Why is everybody using jQuery for something simple as this.
<body OnLoad="document.myform.mytextfield.focus();">
Think about your user interface before you do this. I assume (though none of the answers has said so) that you'll be doing this when the document loads using jQuery's ready() function. If a user has already focussed on a different element before the document has loaded (which is perfectly possible) then it's extremely irritating for them to have the focus stolen away.
You could check for this by adding onfocus attributes in each of your <input> elements to record whether the user has already focussed on a form field and then not stealing the focus if they have:
var anyFieldReceivedFocus = false;
function fieldReceivedFocus() {
anyFieldReceivedFocus = true;
}
function focusFirstField() {
if (!anyFieldReceivedFocus) {
// Do jQuery focus stuff
}
}
<input type="text" onfocus="fieldReceivedFocus()" name="one">
<input type="text" onfocus="fieldReceivedFocus()" name="two">
HTML:
<input id="search" size="10" />
jQuery:
$("#search").focus();
Sorry for bumping an old question. I found this via google.
Its also worth noting that its possible to use more than one selector, thus you can target any form element, and not just one specific type.
eg.
$('#myform input,#myform textarea').first().focus();
This will focus the first input or textarea it finds, and of course you can add other selectors into the mix as well. Handy if you can't be certain of a specific element type being first, or if you want something a bit general/reusable.
This is what I prefer to use:
<script type="text/javascript">
$(document).ready(function () {
$("#fieldID").focus();
});
</script>
place after input
<script type="text/javascript">document.formname.inputname.focus();</script>
The line $('#myTextBox').focus() alone won't put the cursor in the text box, instead use:
$('#myTextBox:text:visible:first').focus();
$("#search").focus();
You can also use HTML5 element <autofocus>
The Simple and easiest way to achieve this
$('#button').on('click', function () {
$('.form-group input[type="text"]').attr('autofocus', 'true');
});

Categories