I have this sample
CODE HTML:
<form method="post" class="add-patient">
<div class="col-md-12">
<fieldset>
<label for="lastname">Phone<span class="star">*</span></label>
<input class="required-input _phone" id="primary_phone" type="text" name="phone" maxlength="10" value="<?php echo $prInfo->clinicphone; ?>" placeholder="1234567890">
</fieldset>
</div>
<div class="col-md-12">
<div class="pull-right" id="save-bottom-add">
<button type="Submit" id="btn-sub" class="btn btn-primary btn-save" onclick="DoSubmit()">Submit</button>
</div>
</div>
</form>
CODE JS:
function DoSubmit(){
var firstFormat = $("#primary_phone").val(); //ex format:(123) 123-1234
var lastFormat = firstFormat.replace(/\s/g, ''); //the new format should be: 123-123-1234
console.log(lastFormat);
return true;
}
What I want to do is transform the format text of an input before submit and pass it in the new format to POST
It is correct that we have chosen method?
What is the solution to transform this format?
Can you help me find a solution to this problem please?
Thanks in advance!
Something like this should get you on track
function DoSubmit(){
var firstFormat = $("#primary_phone").val(); //ex format:(123) 123-1234
var lastFormat = firstFormat.replace(/\D/g,"").replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3'); //new format: 123-123-1234
console.log(lastFormat);
// also do any substitution of value(s) here
// Ex:- $("#primary_phone").val(lastFormat);
return true;
}
$(".add-patient").submit(function() {
DoSubmit();
});
.submit() is a shortcut for .on( "submit", handler ) in the first variation, and .trigger( "submit" ) in the third. See docs
UPDATE: Thanks #titus for pointing out about non-numeric chars.
See the updated code and this fiddle for demo.
Try this:
function DoSubmit(){
var firstFormat = $("#primary_phone").val(); //ex format:(123) 123-1234
//First, replace all non-numeric character then, replace all groups of 3 numbers (not the ending group) with the group itself fallowed by a line.
var lastFormat = firstFormat.replace(/\D/g, "").replace(/(\d{3}(?!$))/g,"$1-");
// Change the input's value to the new one.
$("#primary_phone").val(lastFormat);
return true;
}
Related
I'm trying to get a search field on my site to have an autocomplete/filter function based off of strings in a JSON object. I want to treat the search box as a way to filter out anything that could be in the JSON object.
Here's the search bar in html:
<form id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
And here's the JS for the JSON object, created from a php array:
<script type = "text/javascript">
var orderFormData = <?php Json_encode ($tempdata);?>;
</script>
I'm not sure the best function to use or how to use it on the JSON object, but I've heard JS autocomplete may be a good solution.
Is there a pretty straightforward way to tie these together and have a nice autocomplete/filter function on my search?
This is just given as a proof-of-concept:
<form id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
<script>
var orderFormData = <?php Json_encode ($tempdata);?>;
</script>
<script>
var orderData = orderFormData // default value
var search = function (e) {
var term = e.currentTarget.value
orderData = Object.entries(orderFormData).reduce(function (data, entry) {
if (entry[0].match(term) || entry[1].match(term)) {
data[entry[0]] = entry[1]
}
return data
}, {})
console.log(orderData)
}
document.querySelector('#srch-term').addEventListener('keyup', search)
</script>
This handles the filter part, based on the a match from key/value to the term given in the input.
If you want the autocomplete, then you will have to code much more :)
You forgot to add echo:
<?php echo json_encode($tempdata);?>;
When you are using json_encode, you need to echo or print(). Also make sure you use the right case (optional).
How can I set the ouput of this javascript function as the value for a hidden input on a html form?
document.write(states[i][1]);
works fine but I cannot get it to fill in the value with the code as shown below.
if (to == 'abbr'){
input = input.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
for(i = 0; i < states.length; i++){
if(states[i][0] == input){
document.getElementById("sid").value = (states[i][1]);
}
}
}
}
</script>
<form action="we2.php" method="post">
<input type="text" id="sid" name="s1"/>
<input type="submit" value="Verify">
</form>
What is wrong with this code / what is the right way to do this?
Thanks!
This should do it.
HTML:
<input type="hidden" id="HiddenInput" />
JavaScript:
document.getElementById("HiddenInput").value = someFunction();
Have you checked if states[i][0] == input evaluates to true?
Write JavaScript code after html code end in your page or at the end of page.
I found a easier solution by just turning the entire function into a variable then the variable into the DOM:
var response = abbrState('<?php echo $_GET['state']; ?>', 'abbr');
document.getElementById("sid").value = response;
The following should work.
HTML:
<div style="display:none" id="example"></div>
Javascript:
function addTextNode(text) {
var newtext = document.createTextNode(text),
element = document.getElementById('example');
element.appendChild(newtext);
}
function yourFunctionDataHere(){
return 'test1234';
}
addTextNode(yourFunctionDataHere());
Just make sure, that the return type of your function is of type string. If you want to see the output simply remove the style="display:none" from the div in the above example.
Try it online on jsfiddle.
I have a basic HTML form and I need help creating a bit of JS to redirect my form to different URLs based on the string typed in a text field.
<form class="form-inline">
<div class="form-group">
<input type="text">
<button type="submit">Go</button>
</div>
</form>
There will be 3 or 4 strings of text - to be entered in the input field - that are "valid" and I need them to make the form redirect to various pages on the site.
For instance, typing valid string "STRING1" would make the page redirect to example.com/something.html on form submit, or "STRING2" to example.com/otherpage.html.
But invalid strings would need to go to a page like "example.com/invalid.html."
The most useful thing I've seen so far is this guide: http://www.dynamicdrive.com/forums/showthread.php?20294-Form-POST-redirect-based-on-radio-button-selected
<script type="text/javascript">
function usePage(frm,nm){
for (var i_tem = 0, bobs=frm.elements; i_tem < bobs.length; i_tem++)
if(bobs[i_tem].name==nm&&bobs[i_tem].checked)
frm.action=bobs[i_tem].value;
}
</script>
In that code, each radio has a value assigned to it. But this doesn't help with text fields or having a blanket redirect if the string is invalid.
Thanks so much for your help.
You could define the routes in an object :
<form class="form-inline">
<div class="form-group">
<input type="text">
<button id="submit-form" type="button">Go</button>
</div>
</form>
var urlMapping = {
"STRING1" : "./first.html",
"STRING2" : "./second.html",
"STRING3" : "./third.html"
}
$("#submit-form").click(function(){
var input = $("input").val().trim().toUpperCase();
if (urlMapping.hasOwnProperty(input)){
window.location = urlMapping[input];
}
else {
//if url not found, redirect to default url
window.location = "./default.html";
}
});
Note : I added .toUpperCase() to make it case-insensitive, so you have to be careful to define the urlMapping keys ("STRING1",..) in uppercase.
This should do what you want:
// Define routing:
var validValues = [{
value: 'STRING1',
url: './something.html'
}, {
value: 'STRING2',
url: './otherpage.html'
}];
var $myInput = $('#my-input');
$('#my-button').click(function(ev) {
ev.preventDefault(); // Prevent submitting the form already
// Look for a valid value
var url = './invalid.html';
$.each(validValues, function(i, validValue) {
if ($myInput.val() === validValue.value) {
url = validValue.url;
return false;
}
});
// Submit the form
$('#my-form').prop('action', url).submit();
alert('Redirecting to ' + url);
});
<form class="form-inline" id="my-form">
<div class="form-group">
<input type="text" id="my-input">
<button type="submit" id="my-button">Go</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I currently have a form similar to the below:
<form action="/" method="post" id="myForm">
<div class="row">
<input type="text" name="rowValue" class="rowValue">
</div>
<div class="row">
<input type="text" name="rowValue" class="rowValue">
</div>
<div class="row">
<input type="text" name="rowValue" class="rowValue">
</div>
<div class="row">
<input type="text" name="rowValue" class="rowValue">
</div>
<input type="submit" value="Submit">
</form>
A little background: JS is used to inject X amount of new "rows" into the form.
I tried using:
var myForm = $('#myForm').kendoValidator({
/* rules/messages go here*/
}).data('kendoValidator');
myForm.validate();
I only get one error message showing up on the first input[name='rowValue'].
JS Fiddle
My suspicion is Kendo Validator needs unique name attributes to validate correctly. This is a shame, since lots of backend languages have the ability to accept identical name attributes, as they concatenate the values or convert them into an array or collection (ASP.NET).
Is there a way to have Kendo UI Validator validate form fields with identical name attributes?
Your suspicion is correct. You could adjust the validator for your use case like this:
kendo.ui.Validator.prototype.validateInput = function (input) {
input = $(input);
var that = this,
template = that._errorTemplate,
result = that._checkValidity(input),
valid = result.valid,
className = ".k-invalid-msg",
fieldName = (input.attr("name") || ""),
lbl = input.parent().find("span" + className).hide(),
messageText;
input.removeAttr("aria-invalid");
if (!valid) {
messageText = that._extractMessage(input, result.key);
that._errors[fieldName] = messageText;
var messageLabel = $(template({
message: messageText
}));
that._decorateMessageContainer(messageLabel, fieldName);
if (!lbl.replaceWith(messageLabel).length) {
messageLabel.insertAfter(input);
}
messageLabel.show();
input.attr("aria-invalid", true);
}
input.toggleClass("k-invalid", !valid);
return valid;
};
Note that there are a few simplifications in this method, so it may break on certain corner cases.
(demo)
This is driving me a bit nutty. Javascript link should fire function to fill in div. But not working.
js
function showNotes(notes,id) {
var notes = '<form action="editnotes.php" method="post"><textarea>'+notes+'</textarea><input type="hidden" name="id" value="'+id+'"><input type="submit" name="submit" value="Save Notes"></form>';
var target = 'notebox';
alert(id);
document.getElementById(target).innerHTML = notes;
return false;
}
html
<a href='#' onclick='showNotes('hi there','143');'><small>Show Notes</small></a>
<div id="notebox"></div>
Enclose the onclick attribute value in double quotes, so the single quotes specify a string within your string.
onclick="showNotes('hi there','143');"
http://jsfiddle.net/77CKx/
Shredder got to the heart of the issue. You have nested quotes. However, inline JS is so not cool. Do it with script and the problem goes away. http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/
HTML
<small>Show Notes</small>
JS
document.getElementById('shownotes').onclick = function() {
showNotes('hi there', '143');
return false;
}
It seems like you are breaking the onclick by using the single apostrophe for your function arguments.
Try
<small>Show Notes</small>
Working code:
showNotes = function (notes,id) {
var notes = '<form action="editnotes.php" method="post"><textarea>'+notes+'</textarea><input type="hidden" name="id" value="'+id+'"><input type="submit" name="submit" value="Save Notes"></form>';
var target = 'notebox';
alert(id);
document.getElementById(target).innerHTML = notes;
return false;
}
<small>Show Notes</small>
<div id="notebox"></div>
You can also view it working here:
http://jsfiddle.net/ZMZGk/13/