How to include switch statement in javascript for string - javascript

In my MVC application have included a button called form Field. whenever user clicks on that button dropdownlist gets displayed in modal box that contains text, checkbox etc as option.
code for form field and drop downlist:
<input type="button" id="FormField" name="Form Field" value="Form Field" style="width: 110px; height: 30px; background-color: #FFFFFF;" onclick="return FormField_onclick()" />
function FormField_onclick(box) {
dhtmlx.modalbox({
title: "Form Field Creation Tool",
text: "<div id='form_in_box'><div ><label>Type: <select id='Type' name='Type'><option>Text</option><option>Checkbox</option><option>Radio</option><option>DropDown</option><option>Listbox</option></select></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Select' style='width: 86px' onclick='Select_type(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
width: "300px"
});
}
Whenever user selects particular option from dropdownlist for example if user selects text option and clicks Select button than textbox should get inserted at cursor position.
code for select button:
function Select_type(box) {
var tp = document.getElementById('Type');
switch (tp) {
case "text":
{
var editor = CKEDITOR.instances.message;
editor.insertHtml('<input type="text" id="tx" name="tx" style="width: 110px; height: 30px" />');
}
break;
case "Checkbox": { var editor = CKEDITOR.instances.message;
editor.insertHtml('<input type="checkbox" id="chk" name="chk" value="Checkbox" style="width: 110px; height: 30px" />');}
break;
case "Radio":
{
var editor = CKEDITOR.instances.message;
editor.insertHtml('<input "radio" id="rd" name="rd" value="radio" style="width: 110px; height: 30px" />');
}
break;
case "DropDown": alert("DropDown");
break;
case "Listbox": alert("Listbox");
break;
}
dhtmlx.modalbox.hide(box);
}
but this doesn't work for me. Even the alert doesn't work. And also don't know how can i include dropdown and list in it

You want to do the switch on:
document.getElementById('Type').value
and not on the element it self, as it doesn't equals none of the cases you provided.

You could use an object literal for the switch statement if you wanted to...
var sw = {
hello: function () {
console.log("hello");
},
goodbye: function () {
console.log("goodbye");
}
}
var str = "hello";
sw[str](); //logs hello
Heres an explanation: http://www.dyn-web.com/tutorials/obj_lit.php
I think you need to clarify your question though and tag it appropriately...

Related

Clear form after form post

I am trying to do something a little bit tricky.
I am trying to clear my form, inputs especially after I've submitted the form. Whatever, when I am trying to do so. The form clears but the post never executes. I want it do do both, why it is a little tricky is since I am using so I don't have to reload the page after the form post.
<script>
function submitForm() {
$('form[name="cform"]').submit();
$('input[type="text"], textarea').val('');
return;
}
</script>
<iframe name="target" style="display:none;"></iframe>
<form name="cform" target="target" action="steamauth/chat.php" method="post">
<input type="text" maxlength="120" name="message" style="margin-top: 1vh; margin-left: 2vh; width: 64%">
<button type="submit" name="chat" onclick="submitForm()" style="background-color: #212223; border-radius: 4px; color: black; border: 0px solid #4CAF50; width: 20%; height: 28px;"><font color="white">Send</font></button>
</form>
Is there even a solution?
Using submit() on its own simply submits the form as if the submit button was pressed with no JS present. Additionally, you'll need to use AJAX for what you're after. Try something like this (adapted from the example on https://api.jquery.com/jquery.post/):
<script>
$('form[name="cform"]').submit(function(e) {
e.preventDefault();
var $form = $( this ),
data = $form.serialize(),
url = $form.attr( "action" );
var posting = $.post( url, data );
posting.done(function( data ) {
$('input[type="text"], textarea').val('');
});
});
</script>
<iframe name="target" style="display:none;"></iframe>
<form name="cform" target="target" action="steamauth/chat.php" method="post">
<input type="text" maxlength="120" name="message" style="margin-top: 1vh; margin-left: 2vh; width: 64%">
<button type="submit" name="chat" style="background-color: #212223; border-radius: 4px; color: black; border: 0px solid #4CAF50; width: 20%; height: 28px;"><font color="white">Send</font></button>
</form>
You'll need to further modify to take into account things like submission failures, but that should get you moving in the right direction. I recommend reading through the documentation at the link listed above for more info on callbacks (e.g. .done() in code above).
submitForm() must return true in order to have the form actually submit.
MKM's answer is correct. To clear all input types on a page, use this instead of $('input[type="text"],textarea').val();
This example clears all inputs in three forms. Tested except for select-multiple.
$(':input','#Form1','#Form2','#Form3').each(function()
{
switch(this.type)
{
case "text":
case "textarea":
case "hidden":
{
this.value = ''; break;
}
case "radio":
case "checkbox":
{
this.checked=false; break;
}
case "select-one":
{
// Set dropdowns to default value
$(this).prop("selectedIndex", 0); break;
}
case "select-multiple":
{
$(this).prop("selectedIndex", 0); break;
}
case "file":
{
$(this).value = ""; break;
}
}
});

Select Multiple Input Text Using this.select() — Don't Deselect When Selecting the Next One

I can easily select the text of a textbox for copying to clipboard using:
<input type="text" onclick="this.select();" value="This is my Text">
(i.e. highlight the text so I can click CMD+C to copy to clipboard)
But what I'm trying to do is highlight more than 1 textbox. As soon as I click on another textbox, the previous one gets unselected.
If this is not possible; an alternative approach might be to have a checkbox next to each line of text (in a div or textbox), then click each checkbox I want to select (i.e. highlight the text as if with a mouse), then click CMD+C to copy all of those items to clipboard.
Any ideas?
You can do the following:
Instead of selecting the input, try to toggle a specific class on the input as a response to some user action i.e click, doubleclick etc.
On the above events, add/remove the classes on input.
Add css rules to this specific class such that it appears that it has been selected. Maybe give some border, outline or different background colour.
When you need the text of these inputs, iterate on that specific class and get their value and store them in a textarea which will be hidden from user and then execute the copy command on it.
Here is a quick demo: http://jsfiddle.net/lotusgodkk/GCu2D/2200/
CSS:
.selected {
background: #f0f0f0;
border: 1px solid green
}
textarea {
height: 0;
width: 0;
opacity: 0;
}
HTML:
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<input type="text" value="This is my Text">
<button>
Get Values
</button>
<textarea class="result">
</textarea>
JS:
$(document).ready(function() {
$("input").click(function() {
$(this).toggleClass("selected");
});
$("button").click(function() {
var result = '';
$(".selected").each(function() {
result += $(this).val();
});
$("textarea").val(result);
$("textarea").select();
try {
var text = document.execCommand('copy');//text in clipboard
} catch (err) {
console.log('Error');
}
});
});
The solution from #KK is a good one. Before I saw it, I came up with this other solution so I figured I would post, maybe it helps someone out.
I used a generic html multi-select dropdown for the list of data instead of a series of inputs.
Then I used a JavaScript function found in this question Copy values from html <select multiple> to clipboard which grab the multi-selected values from the select and put them into a with line breaks instead of concatenated like the example.
Then I use clipboard.js to copy the values from the to my clipboard. The default example on the website shows how to do this.
JS
function changeClipboardValue(selectBox) {
var clipboard = document.getElementById("clipboard");
var text = "";
for (i = 0; i < selectBox.length; i++) {
if(selectBox.options[i].selected) text += selectBox.options[i].value + "\r\n";
}
clipboard.value = text;
}
function keydown(e) {
if(e.keyCode === 17) {
var clipboard = document.getElementById("clipboard");
clipboard.select();
}
}
function keyup(e) {
if(e.keyCode === 17) {
var selectBox = document.getElementById("selection");
selectBox.focus();
}
}
HTML for Multi-Select
<select multiple="multiple" size="10" id="selection" onkeydown="keydown(event)" onchange="changeClipboardValue(this)" style="width: 100%; height: 400px;">
HTML for empty Textarea
<textarea id="clipboard" onkeyup="keyup(event)"></textarea>

JavaScript generate new input field on click

I am in the process of making an HTML form where users have different options. I am trying to make a button that infinitely generates a new set op input fields with increasements in the name, like:
The first generated input should have a name of input1. The next with a name of input2 and so on.
Here is a visual example: https://webmshare.com/ZBvw0
How can this be accomplished?
You can solve this problem by creating your form elements dynamically and appending them to your form element.
Below a simplified example, just to show the main idea.
Main points here are:
Document.createElement() - Which creates a specified HTML element (your form elements in this instance).
Node.appendChild() - Which adds a node to the end of the list of children of a specified parent node (your form element in this instance).
(function() {
var counter = 0;
var btn = document.getElementById('btn');
var form = document.getElementById('form');
var addInput = function() {
counter++;
var input = document.createElement("input");
input.id = 'input-' + counter;
input.type = 'text';
input.name = 'name';
input.placeholder = 'Input number ' + counter;
form.appendChild(input);
};
btn.addEventListener('click', function() {
addInput();
}.bind(this));
})();
input{
display: block;
}
<form id="form" action="">
</form>
<button id="btn" type="button">Click Me!</button>
You can use jquery to fetch the name of the last item.
Then you can use the javascript string replace method and replace 'input' with '' in order to get the number of the last item.
Then just increment it by 1. You will have to parse it as an integer before adding 1 to it.
Then with the incremented number, create a new input field and append it to your container.
Try this
HTML
<div id="demo">
</div>
<input type="button" id="add" value="Add input"/>
Javascript
var num = 1;
document.getElementById('add').addEventListener("click",addInput);
function addInput(){
var demo = document.getElementById('demo');
demo.insertAdjacentHTML('beforeend','<div class="form-holder" style="width: 30%;"><a class="form-label">Billet type</a> <br><select name="ttype'+num+'"><option value="normal">Standard Billet</option><option value="add-on">Tilkøbs Billet</option></select></div><div class="form-holder" style="width: 31%; margin-left: 0.6%;"><a class="form-label">Billet navn</a> <br><input name="tname'+num+'" type="text" placeholder="F.eks. Entré Billet" style="width: 100%;" /></div><div class="form-holder" style="float: right; width: 18%; margin-left: 1%;"><a class="form-label">Antal</a> <br><input name="tquan'+num+'" type="text" placeholder="F.eks. 500" style="width: 100%;" /></div><div class="form-holder" style="float: right; width: 18%;"><a class="form-label">Pris (DKK)</a> <br><input name="tprice'+num+'" type="text" placeholder="F.eks. 100" style="width: 100%;" /></div> <br>');
num++;
}
Check out jsFiddle example

Showing suggestion box when typing in input box

I'm trying to get some sort of suggestion box in my application. The basic idea is that, when typing in an input box, 5 options show up below the input box with possible entries.
The problem I am facing is that, while there is nothing entered in the input box, the box which gives the possible suggestions already shows (see Screenshot). Of course, I only want it to show up when I enter something in the input box.
Any help?
Wout
CSS-code:
#suggestions {
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid black;
position: absolute;
left: 310px;
top: 5px;
background-color: white;
font-size: 12px;
}
JavaScript: --> option1, option2,... get a value in function "giveSuggestion()"
<form id = "suggestions">
<input type = "text"
id = "insertText"
autocomplete="off"
onkeyup = "if (event.keyCode == 13) {SearchAddress(option1.text)}
else {giveSuggestion()}"/>
<option id = "option1" onclick = "searchAddress(option1.text)"></option>
<option id = "option2" onclick = "searchAddress(option2.text)"></option>
<option id = "option3" onclick = "searchAddress(option3.text)"></option>
<option id = "option4" onclick = "searchAddress(option4.text)"></option>
<option id = "option5" onclick = "searchAddress(option5.text)"></option>
</form>
There is a standard way of doing that. HTML5 <datalist> tag! And the global browser support for it 74.5%. You may use the above fiddle as a fallback support. Watch this
Check this out:
https://jsfiddle.net/gnph4evm/1/
I have added a new class:
.option{
display:none;
}
and added it to all your options like:
<option class="option" id = "option1" onmousedown = "searchAddress(option1.text)" >text1</option>
added functions for toggling the visibility:
showOptions = function (){
$('.option').show();
}
hideOptions = function (){
$('.option').hide();
}
and for the grand finale, added onfocus and onfocusout calling thoose functions
<input type = "text"
id = "insertText"
autocomplete="off"
onkeyup = "if (event.keyCode == 13) {SearchAddress(option1.text)}
else {giveSuggestion()}" onfocus='showOptions()' onfocusout='hideOptions()'/>
Hope it's helpful
If the Data is stored in the database for suggestion.
Then, after creating the <input> field Make use of <datalist> tag and place it inside a <div> container dynamically replace the content. Here is how you can do it.
<input type="text" name="search_email" list="listit" onkeyup="suggest(this.value)" id="search_email">
<div id="suggest_container" style="display:inline-block;">
<datalist id="listit">
<option ></option>
</datalist>
</div>
Now all you have to do is write Ajax code for it like
function suggest(val){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('suggest_container').innerHTML=this.responseText;
}
};
xhttp.open("GET", ("dyn_suggest.php?value1="+ val), true);
xhttp.send();
}
After this just write the php code for it and check if the $_GET['value1'] is set or not. If not do nothing otherwise fetch the value
$count1=0; // for 5 values
$res=mysqli_query($con,$query);
echo "<datalist id=\"listit\">";
if(mysqli_num_rows($res)!=0){
while($i= mysqli_fetch_row($res)){
$count1++;
echo "<option value='".$i[0]."' >";
if($count1==5){
break;
}
}
}
echo "</datalist>";

select all checkboxes in jquery not triggered properly

I want to set values of selected checkbox to text input
For example: see this image Click
Problem is when i click "Select All" checkbox "child" checkboxes are checked but value not set in textbox and values set when i uncheck the "Select All" checkbox
I want to get checkbox values in array so i am using map function,
Please see jquery on fiddle
fiddle here
HTML CODE
<form action="" id="form">
<input type="checkbox" id="selectAll">
<label for="selectAll">Select All</label><br>
<div class="child">
<input type="checkbox" class="selectCb" value="1" id="one">
<label for="one">One</label><br>
<input type="checkbox" id="two" class="selectCb" value="2">
<label for="two">Two</label><br>
<input type="checkbox" class="selectCb" value="3" id="three">
<label for="three">Three</label><br>
</div>
<input type="text" id="textBox">
</form>
EDIT
Both codes are working
$(document).on("click", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']:checked").map(function() {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
Check on fiddle fiddle 2
$(document).on("change", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']").prop('checked', this.checked).map(function () {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
check on fiddle fiddle 3
Now my doubt is which one is better and correct ?
because i want to set background image for all checkbox, so I hide all checkboxes using css
#form input[type="checkbox"] {
display: none;
}
And set background image for checkbox using following css code
Set Background for "Select All" Checkbox
input[type="checkbox"]#selectAll + label#selectAllLbl::before {
content: '';
background: url('http://s30.postimg.org/uhql9zd5p/chk_uncheck.png') no-repeat;
height: 22px;
width: 22px;
display: inline-block;
margin-right: 10px;
}
input[type="checkbox"]#selectAll:checked + label#selectAllLbl::before {
content: '';
background: url('http://s9.postimg.org/6k81psojf/chk_enabled.png') no-repeat;
}
Set Background for "child" Check boxes
input[type="checkbox"].selectCb + label.childLbl::before {
content: '';
background: url('http://s30.postimg.org/uhql9zd5p/chk_uncheck.png') no-repeat;
height: 22px;
width: 22px;
display: inline-block;
margin-right: 10px;
}
input[type="checkbox"].selectCb:checked + label.childLbl::before {
content: '';
background: url('http://s9.postimg.org/6k81psojf/chk_enabled.png') no-repeat;
}
so is it right ? to use hidden checkbox id and class in jquery
<input type="checkbox" id="selectAll">
<input type="checkbox" class="selectCb" value="1" id="one">
Switch change to click in the second argument:
$(document).on("change", ".selectCb", function () {
var values = $(".child input[type='checkbox']:checked").map(function() {
return $(this).val();
}).get();
$("#textBox").val(values.join(' '));
});
$(document).on("click", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']:checked").map(function() {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
If you want the selectAll to toggle the checks on other checkboxes use prop() to do it. Using this.checked will indicate whether to check or uncheck them
$(document).on("change", "#selectAll", function () {
var chkAll = $(".child input[type='checkbox']").prop('checked', this.checked).map(function () {
return $(this).val();
}).get();
$("#textBox").val(chkAll.join(' '));
});
DEMO
Instead of hiding checkbox you can assign negative margin to it.
Please refer below CSS snippet :
#form {overflow:hidden}
#form input[type="checkbox"]{
margin-left:-25px
}
Also want to repeat what jonmrich has already said to switch "change to click" in the second argument for "#selectAll" checkbox.
Thanks

Categories