Does it make sense to check properties separately or together? - javascript

This question stems from a previous question that I asked. How do you access the for loop of the parent component within a child component which has the inputs?
I want to know is it possible to just check for validity from each property separately instead of together?
So here is the logic that I have for trying to just check for the title input field and then the url field.
onUrlUpdate($event) {
var exp = /\b((http|https):\/\/?)[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/?))/;
// completely overkill, but just used to demonstrate a point
var url = this.urls.find(_url => {
// we can see here that the $event.url is actually the same object as the urls[i] that was
// passed to the child. We do not lose the reference when it is passed to the child or back
// up to the parent.
return $event.url === _url
});
if (url.url.match(exp)) {
url[$event.prop] = $event.newValue;
console.log(`Updated URL's "${$event.prop}" property with the value "${$event.newValue}"`);
} else if(url.title === ''){
console.log('not valid text ');
}
}
The output I am getting is
not valid text
and this is every time I input any text both in the title and url fields. Is there a way for me to check just for the title field? and then use the regex for the url field? Or would I have to split both fields into separate div classes?
Here is the link to the example I am modifying https://stackblitz.com/edit/angular-empty-project-zoy4st?file=app%2Fparent.component.ts

To check for the props separately, all you need to do is add a condition in the update function based on $event.prop. If $event.prop is url, then you validate url, if is title you validate title.
That being said, there is a problem with your current validation. You are checking the value of the existing url object, and not the new value coming in. I have updated it here, it seems to work ok:
https://stackblitz.com/edit/angular-empty-project-tcdfup?file=app/parent.component.ts

Related

how to make input null after submiting?

hello I made a to do list app and I want to clear input after submit here is my code but it doesn't workenter image description here
I expect input section to be null after I submit but every time I have to use backspace then write a new task
First, I would change class="myinput" to id="myinput".
You are assigning user_input to the value of the input at that moment.
Replace your code line to get value by id:
let user_input=document.getElementById("myinput");
let user_input_value=user_input.value;
compare: if(user_input_value!='')
clear with: user_input.value='';
Hi
You just need to save the input element in a variable and set the value property to empty string rather than directly setting user_input = ''.
Also, unless there many inputs you need to loop through, it's better to use id and document.getElementById to identify the input you want rather than document.querySelectorAll
Save the input element as const
const user_input = document.getElementById('myInputId');
// get the value and use as needed
let user_input_value = user_input.value;
After, when you need to reset, set the input elements value to ''
user_input.value = '';

Adding "values" to a texfield in jquery/js

When writing a new email, I've got a modal(pop-up window in boostrap) that shows a list of contacts. When I select (through checkboxes) a couple of contacts, the selected ones are written into a checkbox. Problem is I'm just writing the lastone I select instead of all of the selected ones.
If you need further explanation please ask. (Sorry for my english)
$("#tblContacto").on("click", ".ck", function(event){
if($(".ck").is(':checked')) {
selected_index = parseInt($(this).attr("alt").replace("Check", ""));
var contacto = JSON.parse(tbContactos[selected_index]);
$("#txtDestinatarios").val(contacto.Email);
} else {
$("#txtDestinatarios").val("");
}
});
Assuming that you want to add all E-Mails into a textfield with id txtDestinatariosthe cause of your Problem is the usage of the $("#txtDestinatarios").val(); function.
Calling val() with an argument sets (and thus overwrites) the value within the textfield. (See demo at http://api.jquery.com/val/#val2)
You would have to first retrieve the value of the textfield using code like var currentValue = $("#txtDestinatarios").val() and then add/remove the E-Mail from/to the string before setting the resulting string back as the value.
If you want to set all selected items in the checkboxes into Textfiled you can use the following line of code :-
$("#txtDestinatarios").val( $("#txtDestinatarios").val()+ ","+contacto.Email);

JavaScript populating and clearing <input> textbox

I got 6 "textboxex" and an Array with them.
<input id="slot0" type="text" /> id from 0 to 5, also Array named "slotarray". I want arrray and textboxes to be bound slotarray[0] with input id="slot0" etc.
First i needed function that will find first empty field in array (no matter if corresponding textbox is empty - but should) and put there string (short string - shortcode like "abc" or "sp1").
This function also need to populate bound textbox with long string.
If slotarray[2] == 'abc' then with the same number in ID (here be id="slot2") need to contain long string like "Abrasive Brilliant Conexant".
Here what i got
click to populate
and then function
function populate(shortstring,longstring) {
for (var i=0; i<6; i++) {
if (slotarray[i] == '') {
slotarray[i] = shortsrting;
slotid = 'slot' + i;
document.getElementById(slotid).value = longstring;
break;
}
}
}
With clearing at the moment of creating: ( Array('','','','','','') ), and textbox .value=''; its working as it should.
But then i figured out that i need function to clear textbox and bound array field. Not all but one specific for one clic. So instead of 6 functions i start to wrote
clear this field
for each of textbox, with different numbers and ids ofcourse, and clearing function:
function clear(arrayid, slotid) {
slotarray[arrayid] = '';
document.getElementById(slotid).value = '';
}
But this function do not clearing textbox neither array. I see that textbox has text, and i know that array isn't cleared because first function works finding first empty object...
What am i doing wrong here? its definition of "empty"/"cleared" filed/textbox? maybe i need to use more complex conditions? maybe it is something else.
Maybe i don't need array (i can manage to get rid of short-codes) and just make functions work only on textboxes?
Ok - i prepared jsfiddle demo with this, but even populating don't work..
http://jsfiddle.net/BYt49/11/
You can't use the keyword clear because refers to the (deprecated) function document.clear; so try to change the name of your "clear" function.
Ok, whatever you have written is fine. Just change to way you call your javascript.
Here is jsfiddle: http://jsfiddle.net/BYt49/20/

Moving inline code into function, with object name generation

I am customizing Denis Gritcyuk's Popup date picker.
This pop-up script uses inline Javascript in a href link, to set the selected date into the input field, in the parent window, that is was called for. An example URL looks like:
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.close();">3</a>
The input field name, (e.g. document.formname.field), is passed to the script as a string parameter.
I would like to add things done when that link is clicked (e.g. change background color of field, set flag, etc.). So while this DOES work, it's getting ugly fast.
<a href="javascript:window.opener.document.formname.field.value='03-10-2011';
window.opener.document.formname.field.style.backgroundColor='#FFB6C1';
window.close();">3</a>
How would I move these inline commands into a JS function? This would give me much cleaner URLs and code. The URL would now look something like
3
with a function like (this example obviously does NOT work):
function updateField (str_target, str_datetime) {
var fieldName = "window.opener" + str_target;
[fieldName].value = str_datetime;
[fieldName].style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
So any suggestions on how this can be done, please?
I'd prefer to hide the dom path tracing back from the current window back to the opener. It's appropriate to bake that into the function since the function will always be used in the context of that child popup. Then your function call is cleaner and more readable. Obviously, replace "myField" with the ID of the field you're intending to update.
3
function updateField ( str_date, str_fieldname ) {
var fieldToUpdate = document.getElementById( str_fieldname );
fieldToUpdate.value = str_date;
fieldToUpdate.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
You're acessing the property incorrectly. Try:
function updateField (str_target, str_datetime) {
var fieldName = window.opener;
str_target = str_target.split('.');
for (var i = 0; i < str_target.length; i++)
fieldName = fieldName[str_target[i]];
fieldName.value = str_datetime;
fieldName.style.backgroundColor = '#FFB6C1';
// Set flag, etc.
window.close();
}
The bracket notation ([]) is only used for properties of objects, not objects themselves. If you found my post helpful, please vote for it.
You can build a string and evaluate it as code using the eval function, but I would recommend against it.
There are a couple of things wrong with your code:
You cannot use the [] operator in a global context, you have to suffix it on an object, so you can say window["opener"] and this will be equivalent to window.opener, but there is no such thing as simply ["window"]
When navigating nested properties, as in window.opener.document you cannot navigate multiple levels using the [] operator. I.e. window["opener.document"] is not allowed. You must use window["opener"]["document"] instead.

Javascript: access server side variable client side using variable

I am attempting to:
Use JQuery to 'loop' through all elements on a page that belong to the same CSS class ("boilerplate")
Check the current value of each against it's server side assigned value (property: StaticPrefill)
Apply a special css class ("editedbackcolor") if the two values do not match (ie I'm trying to flag when someone has edited the prefilled text on textboxes)
CSS I am using:
.boilerplate = assign to all text boxes I'm trying to check on the form
.editedbackcolor = different shade I want to assign to textboxes where current value does NOT equal server side StaticPrefill value.
jQuery code I have so far is:
jQuery(document).ready(function () {
// select each element with class boilerplate and run a function against it
jQuery('.boilerplate input').each(function () {
var target1 = jQuery(this).attr("id");
matchcheck(target1);
});
});
and I'm working on the "matchcheck) function which is where I am having a problem. I'm trying to pull back the server side "StaticPrefill" property value that I can use as a comparison. I've successfully queried this by hardcoding a control name, like:
function matchcheck(){
var TSP1 = '<%= TextBox1.StaticPrefill %>';
// If current textbox value does NOT equal it's static prefill value
if (document.getElementById("Textbox1_textbox1").value != TSP1) {
alert("TB1 has differnt value than static prefill");
// change background color to flag it
jQuery("#Textbox1_textbox1").addClass("EditedBackColor");
}
}
That works fine, but I don't want to use a variable to loop through all elements instead of the hardcoded "TextBox1" in the first line of the function. I've tried different syntaxes in an attempt to put a variable between the '<%= ' and '%>' tags but the page won't compile when I try this.
Is this possible w/o using code behind of some sort? Any suggestions?
An easier approach, if I understand your question, is to bind to the change event in jQuery.
$(document).ready(function() {
jQuery('.boilerplate input').change(function() {
if(jQuery(this).val() !== jQuery(this).attr("prefill")) {
jQuery(this)removeClass('boilerplate').addClass("EditedBackColor");
}
});
});
You will also need to add an attribute called "prefill" to your input elements. You can do that server side or client side. It should look something like this:
<input class="boilerplate" id="input1" type="text" prefill="123" value="123"/>
The caveat here is that if they change it back to the original value, it will still show as changed. I'm not sure if that works for you in your scenario. They did change it per se. You would have to save off the original value as an attribute if it did not exist. The other option is to send down a model, maybe a json object, and compare to that model based on index.

Categories

Resources